我正在从外部 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; }
}
这反序列化为空。我认为 TimeSeries 类是正确的,但我不确定如何处理不断变化的日期。使用 json2csharp 不会为我创建有效的类,它告诉我 JSON 无效。
感谢您的帮助。
最佳答案
我正在处理同样的问题并想发布我的解决方案。我使用了您的部分代码并按如下方式完成。我认为它可行,但我才刚刚开始研究它。
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; }
关于c#解析时间序列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44327434/