You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#使用Newtonsoft.Json反序列化嵌套对象JSON数组报错如何解决

问题原因
  • 你拿到的JSON响应最外层是数组结构(用[]包裹),但你原代码尝试将它反序列化为单个Root对象,类型不匹配直接触发了序列化异常
  • 另外你提供的JSON示例里子集合的键是带星号的**childs**,和你定义的childs属性名不一致,不做映射的话反序列化后子集合会为null
解决方案

第一步:修正实体类的键名映射(可选)

如果实际API返回的子集合键确实是带星号的**childs**,需要给属性加特性匹配键名;如果是你写示例时不小心加的星号,实际键就是childs可以跳过这步:

using Newtonsoft.Json;

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; }
    // 匹配JSON里的实际键名,键名无星号就删掉这行
    [JsonProperty("**childs**")]
    public IList<Child> childs { get; set; }
}

第二步:修正反序列化的目标类型

将反序列化目标改为集合类型List<Root>即可:

List<Root> myDeserializedList = JsonConvert.DeserializeObject<List<Root>>(response.Content);

你可以直接遍历拿到的集合使用:

foreach (var item in myDeserializedList)
{
    Console.WriteLine($"ID: {item.id}, 名称: {item.nom}");
    if (item.childs != null)
    {
        foreach (var child in item.childs)
        {
            Console.WriteLine($"  子项ID: {child.id}, 子项名称: {child.nom}");
        }
    }
}

内容的提问来源于stack exchange,提问作者ThierryP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:57:04