如何建模目标类以在 .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 数组位于对象 datamemes 内。对整个响应进行建模,您将能够对其进行反序列化。因此,您将需要以下内容:

    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 下。您仍然可以使用“普通”驼峰式大小写,但您可能必须指示序列化程序不匹配区分大小写的属性名称。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...