Home > Blockchain >  Deserialise JSON data from external api and return a leaner JSON data
Deserialise JSON data from external api and return a leaner JSON data

Time:03-27

I am practicing with web api. My goal is to create a Get endpoint, which receive data from an external api, then return a leaner 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 leaner result like the following:

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

The following code is what I attempted so far, which result is null.. I hope I am not too far away from the right path. Thanks a lot

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

namespace testAPI.Controllers;
public class Content
{
    public List<Meal> Meals { get; set; }
}

public class Meal
{
    [JsonPropertyName("idMeal")]
    public string MealId { get; set; }
    [JsonPropertyName("strMeal")]
    public string Name { get; set; }
}

[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?f=a");
        var request = new RestRequest();
        var response = await client.ExecuteAsync(request);
        var mealList = JsonSerializer.Deserialize<Content>(response.Content);
        var result = JsonSerializer.Serialize(mealList.Meals);
        
        return Ok(result);
    } 

CodePudding user response:

I think the problem is that the deserialization fails because it doesn't know how to deserialize Content.Meals as there's no field in the JSON named Meals - instead it's called meals (lowercase m).

You could fix this by adding the JsonPropertyName attribute to the property in your Content class:

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

Check out this fiddle for a test run.

  • Related