来自外部API的json数据并返回精益的JSON数据
我正在使用Web API练习。我的目标是创建一个从外部API接收数据的GET端点,然后返回更苗条的结果。
外部API链接: https://www.themealdb.com/api/json/v1/1/search.php?f=a
,
外部API数据看起来像:
{
"meals": [
{
"idMeal": "52768",
"strMeal": "Apple Frangipan Tart",
"strDrinkAlternate": null,
"strCategory": "Dessert",
.....
},
{
"idMeal": "52893",
"strMeal": "Apple & Blackberry Crumble",
....
}
]
}
我希望我的终点提供更精细的结果:
[
{
"idMeal": "52768",
"strMeal": "Apple Frangipan Tart"
},
{
"idMeal": "52893",
"strMeal": "Apple & Blackberry Crumble"
}
]
以下代码是我到目前为止尝试的,结果是无效的。我希望我不是离正确的道路太远。非常感谢
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为问题是避免化失败,因为它不知道如何进行
content.meals
,因为JSON中没有字段命名feals
- 而是称为用餐
(小写m
)。您可以通过添加
jsonpropertyname
属性来解决此问题,content
class中的属性:查看用于测试运行的小提琴。
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 namedMeals
- instead it's calledmeals
(lowercasem
).You could fix this by adding the
JsonPropertyName
attribute to the property in yourContent
class:Check out this fiddle for a test run.