0

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);
    } 
dbc
  • 104,963
  • 20
  • 228
  • 340
Blacktea
  • 83
  • 6
  • 2
    Did you try place `[JsonPropertyName("meals")]` for `Meals` property in `Content` class? And you don't need to serialize as JSON string. Just return `Ok(mealList.Meals);`. – Yong Shun Mar 26 '22 at 11:14
  • Thanks a lot Yong shun! I missed that field part – Blacktea Mar 26 '22 at 11:38

1 Answers1

1

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.

Xerillio
  • 4,855
  • 1
  • 17
  • 28