gpt4 book ai didi

c# - 使用 C# 从 json 中反序列化动态对象

转载 作者:太空宇宙 更新时间:2023-11-03 20:50:29 27 4
gpt4 key购买 nike

我有以下 JSON:

{      
"TimeSeries": {
"2019-04-26": {
"open": "20.9000",
"high": "21.0000",
"low": "20.7300",
"close": "20.7300",
"volume": "556200"
},
"2019-04-25": {
"open": "20.8000",
"high": "20.9100",
"low": "20.6600",
"close": "20.7800",
"volume": "784200"
}
}
}

我需要反序列化为 C# 对象。问题是表示日期的列格式是动态的。

我试过使用 Newtonsoft JSON,但无济于事。如何将此 JSON 转换为此对象?

 public class PriceHistory
{
public decimal Open { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal Close { get; set; }
public decimal Volume { get; set; }

//THE PROBLEM IS THIS FIELD
public DateTime Date { get; set; }
}

最佳答案

使用这些类:

public class Root
{
public Dictionary<DateTime, PriceHistory> TimeSeries { get; set; }
}

public class PriceHistory
{
public decimal Open { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal Close { get; set; }
public decimal Volume { get; set; }
}

反序列化:

var json = File.ReadAllText("test.json");
var root = JsonConvert.DeserializeObject<Root>(json);

关于c# - 使用 C# 从 json 中反序列化动态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881168/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com