我从外部API获得JSON响应,我在尝试反序列化时遇到了一些问题。这是JSON:
{
"Time Series (Daily)": {
"2017-06-01": {
"1. open": "70.2400",
"2. high": "70.6100",
"3. low": "69.4510",
"4. close": "70.1000",
"5. volume": "21066468"
},
"2017-05-31": {
"1. open": "70.5300",
"2. high": "70.7400",
"3. low": "69.8100",
"4. close": "69.8400",
"5. volume": "30436364"
}
}
}
以下是我尝试反序列化的类:
public class StockQuote
{
[JsonProperty("Time Series (Daily)")]
public TimeSeriesDaily Daily { get; set; }
}
public class TimeSeriesDaily
{
public string Date { get; set; }
public TimeSeries[] Daily { get; set; }
}
public class TimeSeries
{
[JsonProperty("1. open")]
public string Open { get; set; }
[JsonProperty("2. high")]
public string High { get; set; }
[JsonProperty("3. low")]
public string Low { get; set; }
[JsonProperty("4. close")]
public string Close { get; set; }
[JsonProperty("5. volume")]
public string Volume { get; set; }
}
这反序列化为null。我认为类TimeSeries是正确的,但我不知道如何处理更改日期。使用json2csharp不会为我创建有效的类,它告诉我JSON无效。
感谢您的帮助。
答案 0 :(得分:2)
我正在处理同样的问题,并希望发布我的解决方案。我使用了部分代码并按如下方式完成了它。我认为它有效,但我刚刚开始研究它。
class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "yyyy-mm-dd";
}
}
public class StockQuote
{
[JsonProperty("Time Series (Daily)")]
public Dictionary<string, TimeSeries> tsd { get; set; }
}
public class TimeSeriesDaily
{
[JsonProperty(ItemConverterType = typeof(CustomDateTimeConverter))]
public TimeSeries ts { get; set; }
}
public class TimeSeries
{
[JsonProperty("1. open")]
public string Open { get; set; }
[JsonProperty("2. high")]
public string High { get; set; }
[JsonProperty("3. low")]
public string Low { get; set; }
[JsonProperty("4. close")]
public string Close { get; set; }
[JsonProperty("5. volume")]
public string Volume { get; set; }
}
答案 1 :(得分:0)
我认为你错过了JSON的最后一个卷曲。
答案 2 :(得分:0)
请注意,您正在为对象使用非标准名称。例如,C#变量中不允许使用连字符。变量也不能以数字开头。
生成的类应该看起来像这样。
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace kwcolson98
{
public class StockQuote
{
[JsonProperty("Time Series (Daily)")]
public TimeSeriesDaily _TimeSeriesDaily { get; set; }
public class TimeSeriesDaily
{
[JsonProperty("2017-06-01")]
public TimeSeries _20170601 { get; set; }
[JsonProperty("2017-05-31")]
public TimeSeries _20170531 { get; set; }
public class TimeSeries
{
[JsonProperty("1. open")]
public string Open { get; set; }
[JsonProperty("2. high")]
public string High { get; set; }
[JsonProperty("3. low")]
public string Low { get; set; }
[JsonProperty("4. close")]
public string Close { get; set; }
[JsonProperty("5. volume")]
public string Volume { get; set; }
}
}
}
}