繁体   English   中英

如何使用 Newtonsoft.Json 序列化不同类型的对象列表?

[英]How to serialise a list of objects of different type with Newtonsoft.Json?

在用 c# 编写的应用程序中,我需要创建一个具有特定语法的 JSON 字符串。 要序列化的数据是不同对象的列表。 语法如下所示(整个字符串的一部分):

    "ShipmentUnit": [{
            ...
            "Services": [{
                    "Service1": {
                        "ServiceName": "service_1",
                        "Property1": "Value1",
                        "Property2": "Value2"
                    },
                    "Service2": {
                        "ServiceName": "service_2",
                        "Property3": "Value3",
                    }
                }
            ]
        }
    ]

我想以合适的对象结构提供要序列化的数据,然后使用 Newtonsoft.Json 对其进行序列化。 不幸的是,这不起作用。

如果我对列表使用数组,结果如下所示:

    "ShipmentUnit": [{
            ...
            "Services": [
                    {
                        "ServiceName": "service_1",
                        "Property1": "Value1",
                        "Property2": "Value2"
                    },
                    {
                        "ServiceName": "service_2",
                        "Property3": "Value3",
                    }
                }
            ]
        }
    ]

如果我使用字典,结果如下所示(缺少方括号):

    "ShipmentUnit": [{
            ...
            "Services": {
                "Service1": {
                    "ServiceName": "service_1",
                    "Property1": "Value1",
                    "Property2": "Value2"
                },
                "Service2": {
                    "ServiceName": "service_2",
                    "Property3": "Value3",
                }
            }
        }
    ]

我已经阅读了以下主题,但它们与我的问题不符:

序列化 C# 自定义对象的列表

将对象列表序列化为单个 JSON 对象,以属性为键

序列化列表<字典<字符串,对象>>

有什么想法该怎么做?

尝试这个

    Data data=JsonConvert.DeserializeObject<Data>(json);
    
    json=JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);

班级

public class Data
{
    public List<ShipmentUnit> ShipmentUnit { get; set; }
}
public class ShipmentUnit
{
    public List<Dictionary<string,Dictionary<string,string>>> Services { get; set; }
}

结果

{
  "ShipmentUnit": [
    {
      "Services": [
        {
          "Service1": {
            "ServiceName": "service_1",
            "Property1": "Value1",
            "Property2": "Value2"
          },
          "Service2": {
            "ServiceName": "service_2",
            "Property3": "Value3"
          }
        }
      ]
    }
  ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM