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

C#中使用Newtonsoft.Json实现指定嵌套JSON序列化的问题

问题解决:Newtonsoft.Json序列化目标JSON的问题

目标JSON格式

{
    "testsystem": "1.0.0",
    "playback": { 
       "1": {
          "cue": 1,
          "state": "Stopped",
          "label": "Hello"
       },
       "2": {
          "cue": 100,
          "state": "Running",
          "label": "Hello"
       }
    }
}

现有问题

  • 无法在playback下生成多个键值对,for循环赋值时出现语法错误;
  • 序列化结果出现重复的playback字段,输出异常:
{
  "testsystem": "1.0.0",
  "playback": {
    "playback": 0,
    "cue": {
      "cue": "34",
      "state": "Running",
      "label": "Hello World"
    }
  }
}

问题根源分析

  1. 类结构完全不符合目标JSON:目标里playback是键为字符串/数字、值为cue对象的字典,但你定义的pb类是包含冗余playback字段和单个cue对象的普通类,结构不匹配;
  2. 对象初始化器语法错误:不能在对象初始化器内部直接写for循环,必须先初始化对象再单独执行循环逻辑。

修正方案

1. 修改类定义

删除多余的pb类,把Company中的playback改为字典类型,直接匹配目标结构:

public class Company
{
    [JsonProperty("testsystem")]
    public string TestSystem { get; set; }

    [JsonProperty("playback")]
    public Dictionary<string, Cue> Playback { get; set; } = new Dictionary<string, Cue>();
}

public class Cue
{
    [JsonProperty("cue")]
    public int CueNumber { get; set; } // 目标JSON中cue是数字,用int类型更匹配

    [JsonProperty("state")]
    public string State { get; set; }

    [JsonProperty("label")]
    public string Label { get; set; }
}

2. 修正序列化代码

先初始化Company对象,再通过for循环向字典中逐个添加键值对:

Company thisCompany = new Company
{
    TestSystem = "1.0.0"
};

// 循环生成playback下的多个条目
for (int pb = 1; pb < 7; pb++)
{
    thisCompany.Playback.Add(pb.ToString(), new Cue
    {
        CueNumber = int.Parse(Globals.QNumber[pb]), // 假设QNumber是字符串数组,转成int匹配目标格式
        State = Globals.QState[pb],
        Label = Globals.QLabel[pb]
    });
}

string json = JsonConvert.SerializeObject(thisCompany, Formatting.Indented);

关键说明

  • 用Dictionary<string, Cue>直接对应目标JSON中playback的键值对结构,序列化后自动生成"1""2"这类字符串键;
  • 修正了对象初始化器的语法错误,把循环逻辑移到初始化器外部执行;
  • 调整Cue类的字段类型,匹配目标JSON中cue为数字的格式,避免类型不匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:55:34