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

时间:2019-04-27 13:44:03

标签: c# json json.net

我有以下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; }
    }

1 个答案:

答案 0 :(得分:4)

使用这些类:

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);