c# > Json 使用 "recurrent objects" 反序列化
c# > Json Deserialize with "recurrent objects"
我正在使用 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; }
}
我正在使用 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; }
}