簡體   English   中英

超長對象的嵌套反序列化 - 從 Json 到 C#

[英]Nested Deserialization of a Very Long Object - From Json to C#

我想將以下字符串對象(JSON 字符串)反序列化為 C# 列表。 請注意,這是 JSON 格式,而不是 C# 轉義字符等。

{
  "2020-01-01": 
  {
    "price" : 100
  },
  "2020-01-02": 
  {
    "price" : 101
  },
  "2020-01-03": 
  {
    "price" : 103
  },
  "2020-01-04": 
  {
    "price" : 104
  },
... 
}

期望的結果將是一個對象列表,例如:

class DataPoint 
{
   public string Date { get; set;}
   public int Price { get; set;}
}

例如結果應該是這樣的

{{"2020-01-01", 100},
{"2020-01-02", 101},
{"2020-01-03", 103},
{"2020-01-04", 104}}

請注意, https://json2csharp.com/解決方案對我來說是不可接受的,因為日期可能很多,並且不可能像那里建議的那樣編寫一個涵蓋所有數據點的類。

您能否建議一種將原始字符串 JSON 對象反序列化為 C# 集合的 List 類型的方法?

創建一個這樣的類:

public class Price
{
    public int price { get; set; }
}

然后將您的 JSON 反序列化為Dictionary<string, Price>如下所示:

var results = JsonConvert.DeserializeObject<Dictionary<string, Price>>(data);

一旦你在字典中擁有它,你可以像這樣構建你的DataPoint類的項目集合:

var items = new List<DataPoint>();
foreach (var item in results)
{
    items.Add(new DataPoint {Date = item.Key, Price = item.Value.price});
}

或者如果你喜歡大長的 LINQ 表達式:

var items = results.Select(item => new DataPoint {Date = item.Key, Price = item.Value.price}).ToList();

這會給你你正在尋找的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM