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

C# JSON反序列化失败:ID被识别为类型问题求助

解决JSON反序列化失败的问题

你这是踩了个典型的JSON结构匹配坑——你的JSON根本不是数组,而是一个以ID为键、目标数据为值的字典对象,直接用List<JsonResultCustom>去反序列化肯定会失败,因为两者结构完全不匹配。

具体解决方案

你需要先把JSON反序列化成字典类型,再提取其中的值转换成List:

  1. 调整反序列化代码
    把原来的List反序列化改成字典:

    var resultDict = JsonConvert.DeserializeObject<Dictionary<string, JsonResultCustom>>(rawjson);
    

    这里用string作为键的类型,因为JSON里的ID(比如"13294")本质是字符串形式的键。

  2. 转换成List(如果需要)
    要是你最终还是需要List<JsonResultCustom>,只需要取字典的Values集合转换就行:

    List<JsonResultCustom> resultList = resultDict.Values.ToList();
    

额外注意点

别忘了检查你的SplashImage类是否正确定义——JSON里包含splash_image字段,这个类的属性必须和JSON中该字段的子结构完全匹配,否则也会导致反序列化失败。比如如果splash_image包含url和width字段,你的类应该是:

public class SplashImage
{
    public string url { get; set; }
    public int width { get; set; }
    // 其他对应字段...
}

举个实际的例子,假设你的JSON是:

{
  "13294": {
    "blurb": "Proin tellus enim...",
    "splash_image": { "url": "example.jpg", "width": 800 },
    "title": "Sample Title",
    "permalink": "/sample"
  },
  "13350": {
    "blurb": "Another content...",
    "splash_image": { "url": "another.jpg", "width": 600 },
    "title": "Another Title",
    "permalink": "/another"
  }
}

用上面的代码就能顺利把每个ID对应的对象反序列化出来,再转成List使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:48:12