如何解决如何建模目标类以在 .NET5 中接收 JSON html 响应
我正在尝试从提供包含对象数组的 JSON 文件的公共 WEB Api 读取对象列表,我正在使用 Blazor 和 Net 5 平台。
反序列化失败并出现此错误:
System.Text.Json.JsonException: The JSON value Could not be converted to Meme[].
我怀疑我对“接收”对象的建模不正确,我应该更改我的代码还是使用其他库来使此代码成功?
可以在 this endpoint 找到 Api,我尝试通过以下两种方式阅读响应:
var response = await Http.GetFromJsonAsync<Meme[]>("https://api.imgflip.com/get_memes");
和
var httpResponse = await Http.GetAsync("https://api.imgflip.com/get_memes");
var response = await httpResponse.Content.ReadFromJsonAsync<Meme[]>();
Meme 类声明如下:
public string Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int BoxCount { get; set; }
并且响应应包含以下内容:
"success": true,"data": {
"memes": [
{
"id": "181913649","name": "Drake Hotline Bling","url": "https://i.imgflip.com/30b1gx.jpg","width": 1200,"height": 1200,"Box_count": 2
},{
...
},... ]
}
这些是我包含的库:
using System.Net.Http;
using System.Net.Http.Json;
解决方法
响应中包含的不仅仅是您的模因本身。 Meme 数组位于对象 data
和 memes
内。对整个响应进行建模,您将能够对其进行反序列化。因此,您将需要以下内容:
public class Response
{
public bool success { get; set; }
public Data data { get; set; }
}
public class Data
{
public Meme[] memes { get; set; }
}
public class Meme
{
public string id { get; set; }
public string name { get; set; }
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
public int box_count { get; set; }
}
// Now you can use that like this:
var response = await httpResponse.Content.ReadFromJsonAsync<Response>();
请注意,VS 中有一个方便的工具为我生成了它。您可以将 JSON 作为类粘贴到 Edit > Paste Special > Paste JSON as Classes
下。您仍然可以使用“普通”驼峰式大小写,但您可能必须指示序列化程序不匹配区分大小写的属性名称。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。