Home > Back-end >  class property manipulation when parsing json data in c#
class property manipulation when parsing json data in c#

Time:03-28

I am practicing with web api. My goal is to create a Get endpoint, which receive data from an external api, then return a different result. external api link: https://www.themealdb.com/api/json/v1/1/search.php?f=a, The external api data looks like:

{
  "meals": [
    {
      "idMeal": "52768",
      "strMeal": "Apple Frangipan Tart",
      "strDrinkAlternate": null,
      "strCategory": "Dessert",
      .....
    },
    {
      "idMeal": "52893",
      "strMeal": "Apple & Blackberry Crumble",
      ....
     }
   ]
}

I want my endpoint provide a different result like the following:

[
    {
      "idMeal": "52768",
      "strMeal": "Apple Frangipan Tart",
      "ingredients": ["Apple", "sugar"...]
    },
    {
      "idMeal": "52893",
      "strMeal": "Apple & Blackberry Crumble",
      "ingredients": ["Apple", "sugar"...]
     }
 ] 

The following code is what I attempted so far, It's working, but the moment I changed property ingredient1 from public to private, that ingredient in list will become null, also, there are so many ingredients, some of them are null by default, I don't want to add them if they are null, how can I fix these two issues? Thanks a lot

using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;
using RestSharp;

namespace testAPI.Controllers;
public class Content
{
    [JsonPropertyName("meals")]
    public List<Meal> Meals { get; set; }
}

public class Meal
{
    [JsonPropertyName("idMeal")]
    public string MealId { get; set; }
    [JsonPropertyName("strMeal")]
    public string Name { get; set; }
    [JsonPropertyName("strIngredient1")]
    public string Ingredient1 { get; set; }
    [JsonPropertyName("strIngredient2")]
    public string Ingredient2 { get; set; }
    [JsonPropertyName("strIngredient20")]
    public string Ingredient20 { get; set; }

    public List<string> Ingredients
    {
        get { return new List<string>(){Ingredient1, Ingredient2, Ingredient20};} 
    }
}

[ApiController]
[Route("api/[controller]")]
public class DishesController : ControllerBase
{
    
    [HttpGet]
    public async Task<IActionResult> GetAllRecipes()
    {
        var client = new RestClient($"https://www.themealdb.com/api/json/v1/1/search.php?s=");
        var request = new RestRequest();
        var response = await client.ExecuteAsync(request);
        var mealList = JsonSerializer.Deserialize<Content>(response.Content);
        
        return Ok(mealList.Meals);
    }
    
}

CodePudding user response:

To address the problems one at a time...

the moment I changed property ingredient1 from public to private, that ingredient in list will become null

Changing the access modifier affects both deserialization and serialization, so this cannot be used to only stop it from serializing the property. You should split the data models up into what you want to receive and what you want to expose/return.

there are so many ingredients, some of them are null by default, I don't want to add them if they are null

Addition to splitting up the data models you can handle this when mapping from one model to the other.

The following code should fix both issues:

namespace TheMealDb.Models
{
    // These are the models you receive from TheMealDb
    // JSON converted to classes with https://json2csharp.com/
    public class Root
    {
        public List<Meal> meals { get; set; }
    }
    
    public class Meal
    {
        public string idMeal { get; set; }
        public string strMeal { get; set; }
        public string strIngredient1 { get; set; }
        public string strIngredient2 { get; set; }
        public string strIngredient3 { get; set; }
        // Other properties removed for brevity...
    }
}

namespace Internal.Models
{
    // This is the model you want to return from your controller action
    public class Meal
    {
        [JsonPropertyName("id")] // No need to use the same name as from themealdb
        public string Id { get; set; }
        [JsonPropertyName("name")]
        public string Name { get; set; }
        [JsonPropertyName("ingredients")]
        public List<string> Ingredients { get; set; }
    }
}

Now, to fetch, map and return the data in your controller action:

[HttpGet]
public async Task<IActionResult> GetAllRecipes()
{
    var client = new RestClient($"https://www.themealdb.com/api/json/v1/1/search.php?s=");
    var request = new RestRequest();
    var response = await client.ExecuteAsync(request);

    // Deserialize to the "TheMealDb" models
    var mealList = JsonSerializer.Deserialize<TheMealDb.Models.Root>(response.Content);
    // Map to your own models
    var myMealList = mealDbList.meals?.Select(MapToInternal);
        
    return Ok(myMealList);
}

// Map "TheMealDb" model to your own model
private Internal.Models.Meal MapToInternal(TheMealDb.Models.Meal externalMeal)
{
    return new Internal.Models.Meal
    {
        Id = externalMeal.idMeal,
        Name = externalMeal.strMeal,
        Ingredients = new []
            {
                externalMeal.strIngredient1,
                externalMeal.strIngredient2,
                externalMeal.strIngredient3,
                // ...
            }
            // Remove empty/null ingredients
            .Where(ingr => !string.IsNullOrEmpty(ingr))
            .ToList()
    };
}

See the code in action.

  • Related