c# - c# > 使用“循环对象”反序列化 Json
问题描述
我正在使用 Visual Studio 和 C#,我是初学者.... :-(
我想反序列化这个 json 响应:
[
{
"id": 10076,
"nom": "00 Test Api Upload"
},
{
"id": 9730,
"nom": "2021 Vacances Sabran Gruissan",
"**childs**": [
{
"id": 9731,
"nom": "Gruissan"
},
{
"id": 9745,
"nom": "Sabran"
}
]
}
]
我尝试这样做:
public class Child
{
public int id { get; set; }
public string nom { get; set; }
}
public class Root
{
public int id { get; set; }
public string nom { get; set; }
public IList<Child> childs { get; set; }
}
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(response.Content);
但是不行
我有这种错误:
Newtonsoft.Json.JsonSerializationException:'无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'GpxToolZ.VisuGpx+Root',因为该类型需要 JSON 对象(例如 {"name":"value"} ) 以正确反序列化。要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化。JsonArrayAttribute 也可以添加到类型中以强制它从 JSON 数组反序列化。路径'',第 1 行,位置 1。
有人可以帮助我吗?
谢谢。
解决方案
您有一个对象数组,而不仅仅是一个对象,因此请尝试使用 Root[] 代替 Root 或尝试此代码
var jD = JsonConvert.DeserializeObject<Data[]>(json);
班级
public partial class Data
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("nom")]
public string Nom { get; set; }
[JsonProperty("childs", NullValueHandling = NullValueHandling.Ignore)]
public Child[] Childs { get; set; }
}
public partial class Child
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("nom")]
public string Nom { get; set; }
}
推荐阅读
- ruby-on-rails - 使用 find_each 时有没有办法按特定列排序?
- javascript - 使用 chrome 扩展在 contetnteditable 中下划线文本
- javascript - React 性能 - DOM 样式和组件渲染
- python - svc.predict 可以返回结果以及其他类的概率吗?
- amazon-web-services - AWS Cognito 身份验证失败时无法获取有效的错误代码
- performance - 应用服务器或 Web 服务器性能哪个更好?
- c# - 在 ASP.Net Core 3.x DI 中配置 System.Text.Json Camel Case
- java - Java:如何构造或模式化一个类,以便我们可以在运行时映射组合的对象?
- bash - Synology diskstation bash 脚本:删除旧文件(仅保留 10 个最新文件)
- c# - 在 windows 窗体上绘制一个移动的矩形