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

使用NewtonSoft反序列化属性名为数字的JSON数据遇阻

问题

对接美国劳工统计局数据时,使用NewtonSoft反序列化JSON响应,其中calculations节点结构如下:

"calculations": {
    "net_changes": {
        "1": "133",
        "3": "220",
        "6": "1985",
        "12": "2949"
     },
     "pct_changes": {
        "1": "0.1",
        "3": "0.1",
        "6": "1.2",
        "12": "1.8"
      }
}

对应的C#类定义如下:

public class Calculations
{
    public Net_Changes net_changes { get; set; }
    public Pct_Changes pct_changes { get; set; }
}

public class Net_Changes
{
    public string _1 { get; set; }
    public string _3 { get; set; }
    public string _6 { get; set; }
    public string _12 { get; set; }
}

public class Pct_Changes
{
    public string _1 { get; set; }
    public string _3 { get; set; }
    public string _6 { get; set; }
    public string _12 { get; set; }
}

反序列化根对象后,calculations始终为null,但Postman显示数据正常返回,需要实现JSON中数字键(如"1")映射到类中带下划线的属性(如_1)。

解决方案

方法一:用JsonProperty特性显式映射键名

NewtonSoft默认按属性名匹配JSON键,由于JSON键是纯数字、C#属性是带下划线的命名,需要通过JsonProperty特性指定对应关系,修改后的类如下:

public class Calculations
{
    public Net_Changes net_changes { get; set; }
    public Pct_Changes pct_changes { get; set; }
}

public class Net_Changes
{
    [JsonProperty("1")]
    public string _1 { get; set; }
    [JsonProperty("3")]
    public string _3 { get; set; }
    [JsonProperty("6")]
    public string _6 { get; set; }
    [JsonProperty("12")]
    public string _12 { get; set; }
}

public class Pct_Changes
{
    [JsonProperty("1")]
    public string _1 { get; set; }
    [JsonProperty("3")]
    public string _3 { get; set; }
    [JsonProperty("6")]
    public string _6 { get; set; }
    [JsonProperty("12")]
    public string _12 { get; set; }
}

反序列化时,NewtonSoft会根据JsonProperty指定的键名,自动将JSON中的"1"映射到_1属性,以此类推。

方法二:改用Dictionary<string, string>简化结构

如果不需要固定属性,可将net_changes和pct_changes定义为字典类型,无需手动映射每个键,更灵活:

public class Calculations
{
    public Dictionary<string, string> net_changes { get; set; }
    public Dictionary<string, string> pct_changes { get; set; }
}

反序列化后,可直接通过calculations.net_changes["1"]获取对应值,适合键数量可能变动的场景。

反序列化验证示例

确保使用NewtonSoft的标准反序列化方法:

var json = "你的完整JSON响应字符串";
var rootObj = JsonConvert.DeserializeObject<RootClass>(json);

(注:RootClass是包含calculations属性的根类,需自行定义)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 21:10:00