c# - 将 JSON 响应数据反序列化到列表中的问题
问题描述
我在将数据中的元素放入列表时遇到问题。
我希望能够将User_ID
、Country
和Continent
其他元素添加到列表中,之后我将对数据库进行批量插入。
错误我收到 错误消息 mscorlib.dll 中发生“Newtonsoft.Json.JsonSerializationException”类型的异常,但未在用户代码中处理
附加信息:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[Country_API.Response]”,因为该类型需要 JSON 数组(例如 [1 ,2,3]) 以正确反序列化。
要修复此错误,请将 更改JSON
为JSON
数组(例如 [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; }
}
请问我该如何实现?
解决方案
您正在尝试反序列化对象内的 List 。您需要反序列化整个对象。尝试这个:
if (result.IsSuccessStatusCode)
{
string toJsonString = await result.Content.ReadAsStringAsync();
var deserialize = JsonConvert.DeserializeObject<Application>(toJsonString);
IList<Data> dataList = deserialize.Response.data;
}
推荐阅读
- sparse-matrix - 来自R中给定csv文档术语矩阵的lda主题建模交叉验证
- cocoa - 如何让 NSSavePanel 使用系统语言?
- azure - Azure Function v3 无法将 blob 绑定到 CloudBlockBlob
- javascript - 无法更改 Chart.js 的大小
- tcl - Innovus 中的 report_timing 到变量
- python - 我在 Pygame 中使用 .blit() 做错了什么?
- node.js - Discord JS如何从Web(JSON)读取和发送数据
- powershell - Get-ADUser:无效类型“System.String[]”
- java - Java spring boot:在嵌套对象中包含嵌套对象属性
- c++ - 类中一种方法的部分特化