首页 > 解决方案 > 将 JSON 响应数据反序列化到列表中的问题

问题描述

我在将数据中的元素放入列表时遇到问题。

我希望能够将User_IDCountryContinent其他元素添加到列表中,之后我将对数据库进行批量插入。

错误我收到 错误消息 mscorlib.dll 中发生“Newtonsoft.Json.JsonSerializationException”类型的异常,但未在用户代码中处理

附加信息:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[Country_API.Response]”,因为该类型需要 JSON 数组(例如 [1 ,2,3]) 以正确反序列化。

要修复此错误,请将 更改JSONJSON数组(例如 [1,2,3])或更改反序列化类型,使其成为普通.NET类型(例如,不是像整数这样的原始类型,不是像数组这样的集合类型或List<T>)可以从JSON对象反序列化。JsonObjectAttribute也可以添加到类型中以强制它从JSON对象反序列化。

这是从 API 返回的 JSON 数据

{
    "Status": "200 Ok",
    "Message": "Data retrieved",
    "Response": {
        "current_page": 1,
        "data": [
            {
                "User-ID": "EAD001",
                "Country": "Ghana",
                "Continent": "Africa",
                "Gender": "Male",
                "Email": "ead1@yahoo.com",
                "Religion": ""
            },
            {
                "User-ID": "EAD002",
                "Country": "Senegal",
                "Continent": "Africa",
                "Gender": "Female",
                "Email": "ead2@yahoo.com",
                "Religion": "Muslim"
            }
        ]
    }
}

我正在尝试反序列化,但它会引发上述错误..这就是我正在尝试的

if (result.IsSuccessStatusCode)
{
    string toJsonString = await result.Content.ReadAsStringAsync();

    var deserialize = JsonConvert.DeserializeObject<List<Response>>(toJsonString);
}

json模型

public class Data
{
    public string User-ID { get; set; }
    public string Country { get; set; }
    public string Continent { get; set; }
    public string Gender { get; set; }
    public string Email { get; set; }
    public string Religion { get; set; }

}
public class Response
{
    public int current_page { get; set; }
    public IList<Data> data { get; set; }

}
public class Application
{
    public string Status { get; set; }
    public string Message { get; set; }
    public Response Response { get; set; }
}

请问我该如何实现?

标签: c#json

解决方案


您正在尝试反序列化对象内的 List 。您需要反序列化整个对象。尝试这个:

if (result.IsSuccessStatusCode)
{
    string toJsonString = await result.Content.ReadAsStringAsync();

    var deserialize = JsonConvert.DeserializeObject<Application>(toJsonString);
    IList<Data> dataList = deserialize.Response.data;
}

推荐阅读