簡體   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