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

C#中用Newtonsoft.Json解析含动态属性的JSON问题

问题:C# 使用Newtonsoft.Json解析混合固定与动态属性的JSON

原始JSON数据

[  
  {
    "Example1": value1,  
    "Example2": value1,  
    "Example3": "value1",  
    "ExampleList": {    
      "Example4": "",      
      "Example5": "value1",      
      "Example6": "value1",      
      "Example7": "",      
      "Example8": "value1"
    },  
    "Example9": ["value1"],  
    "Example10": []  
  }
]

问题详情

解析时卡在ExampleList、Example9和Example10三个字段上:

  • ExampleList的属性数量不固定,可能是5个,也可能是20个;之前单独解析该字段时,用Dictionary<string, string>可以正常处理,但和其他固定属性结合时出现问题
  • Example9和Example10是数组类型

尝试的错误代码

最初参考方案编写的类结构:

public partial class ExampleClass
{
    public int Example1 { get; set; }
    public long Example2 { get; set; }
    public long Example3 { get; set; }
    public ExampleList exampleList { get; set; }
}

public partial class ExampleList
{
    Dictionary<string, string> exampleList = new Dictionary<string, string>();
}

运行时抛出错误:

JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Models.ExampleClass' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

可行解决方案

调整类结构,直接将ExampleList定义为Dictionary<string, string>,同时为Example9和Example10定义数组类型:

public class ExampleClass
{
    public int Example1 { get; set; }
    public int Example2 { get; set; }
    public int Example3 { get; set; }
    public Dictionary<string,string> ExampleList { get; set; }
    public string[] Example9 { get; set; }
    public string[] Example10 { get; set; }
}

反序列化代码:

var tempAttr = JsonConvert.DeserializeObject<List<ExampleClass>>(response);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:25:17