如何使用Newtonsoft.Json序列化不同类型对象列表并生成指定结构的JSON?
解决思路:匹配目标JSON结构的C#对象设计
你的核心问题是要让Services成为一个包含单个键值对集合的数组——也就是数组里的元素是一个字典,这个字典以Service1、Service2为键,对应的服务对象为值。之前的尝试要么是数组直接存服务对象(缺少外层键),要么是直接用字典(把数组变成了普通对象),所以都不符合要求。
下面是具体的实现方案:
方案1:强类型实体类(推荐,类型安全)
首先定义服务的实体类,以及包含Services属性的ShipmentUnit类:
// 服务实体类,根据你的需求定义属性 public class Service { public string ServiceName { get; set; } public string Property1 { get; set; } public string Property2 { get; set; } public string Property3 { get; set; } } public class ShipmentUnit { // 这里Services的类型是List<Dictionary<string, Service>>:数组(List)里每个元素是一个字典 public List<Dictionary<string, Service>> Services { get; set; } // 其他ShipmentUnit的属性... }
然后实例化并序列化:
// 创建服务对象 var service1 = new Service { ServiceName = "service_1", Property1 = "Value1", Property2 = "Value2" }; var service2 = new Service { ServiceName = "service_2", Property3 = "Value3" }; // 把多个服务放到一个字典里 var serviceDictionary = new Dictionary<string, Service> { { "Service1", service1 }, { "Service2", service2 } }; // 把字典放到List里(这样序列化后就是数组格式) var shipmentUnit = new ShipmentUnit { Services = new List<Dictionary<string, Service>> { serviceDictionary } }; // 序列化输出 var json = JsonConvert.SerializeObject(shipmentUnit, Formatting.Indented);
这样生成的JSON就会完全匹配你要的结构:
"ShipmentUnit": [ { "Services": [ { "Service1": { "ServiceName": "service_1", "Property1": "Value1", "Property2": "Value2" }, "Service2": { "ServiceName": "service_2", "Property3": "Value3" } } ] } ]
方案2:动态字典(适合属性不固定的场景)
如果你的服务属性是动态变化的,不想定义固定的实体类,可以直接用Dictionary<string, object>来构建:
// 动态构建服务对象 var service1 = new Dictionary<string, object> { { "ServiceName", "service_1" }, { "Property1", "Value1" }, { "Property2", "Value2" } }; var service2 = new Dictionary<string, object> { { "ServiceName", "service_2" }, { "Property3", "Value3" } }; // 构建包含服务的字典 var serviceDict = new Dictionary<string, object> { { "Service1", service1 }, { "Service2", service2 } }; // 放到List中确保数组格式 var shipmentUnit = new Dictionary<string, object> { {"ShipmentUnit", new List<object> { new Dictionary<string, object> { { "Services", new List<object> { serviceDict } } } }} }; var json = JsonConvert.SerializeObject(shipmentUnit, Formatting.Indented);
这个方案不需要定义实体类,灵活性更高,但失去了类型安全的优势。
为什么之前的尝试失败?
- 用
List<Service>:序列化后数组里直接是服务对象,没有Service1、Service2这些键,不符合目标结构。 - 用
Dictionary<string, Service>作为Services的类型:序列化后Services会变成普通对象(用{}包裹),而不是数组(用[]包裹),和目标结构不符。
内容的提问来源于stack exchange,提问作者Daelian
相关产品推荐
相关产品推荐

