首页 > 解决方案 > 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。

有人可以帮助我吗?

谢谢。

标签: c#jsonserialization

解决方案


您有一个对象数组,而不仅仅是一个对象,因此请尝试使用 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; }
}

推荐阅读