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

Newtonsoft.Json反序列化JSON列表时Dictionary属性为空如何解决?

问题:Newtonsoft.Json反序列化时VatRateSum始终为null,是否需要使用JsonConverter?

定义的TransactionResponse类

public class TransactionResponse
{
     public string Serial { get; set; }
     public int Amount{ get; set; }
     public long Date { get; set; }
     public Dictionary<string, int> VatRateSum { get; set; }
     public string Type { get; set; }
     public int Number { get; set; }
     public bool Refund { get; set; }
     public string ErrorMessage { get; set; }
}

对应的JSON响应

[{      
  "Serial": "SSN-123456789",
  "Amount": 1000,
  "Date": 1659571200000,
  "VatRateSum": {
     "6": 1000
  },
  "Number": 647,
  "Type": "Normal",
  "ErrorMessage": null,
  "Refund": false
},
{
  "Serial": "SSN-123456789",
  "Amount": 2000,
  "Date": 1659571200000,
  "VatRateSum": {
     "6": 1000,
     "12": 1000
  },
  "Number": 646,
  "Type": "Normal",
  "ErrorMessage": null,
  "Refund": false
}]

反序列化代码

List<TransactionResponse> responseResult = JsonConvert.DeserializeObject<List<TransactionResponse>>(resultInfo);

解答

不需要急着用JsonConverter,先排查几个常见问题:

  • 核对键名大小写匹配:你提供的示例里VatRateSum的大小写完全一致,但实际接口返回的JSON可能存在拼写或大小写错误(比如写成vatRateSum)。如果是这种情况,给类的属性加上[JsonProperty]特性明确指定对应键名即可:

    [JsonProperty("VatRateSum")]
    public Dictionary<string, int> VatRateSum { get; set; }
    
  • 检查序列化配置:确认是否自定义了ContractResolver或设置了忽略规则,导致Dictionary<string, int>类型的属性被跳过反序列化。

  • 验证Newtonsoft.Json版本:过低的版本可能对泛型字典的反序列化存在兼容问题,尝试升级到较新的稳定版本。

你的示例代码和JSON结构本身是匹配的,正常情况下Newtonsoft.Json可以直接把{"6":1000}这类结构反序列化为Dictionary<string, int>,只有在上述排查都无法解决时,才需要考虑自定义JsonConverter。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 07:24:19