c#解析时间序列数据

标签 c# json json-deserialization

我正在从外部 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/

相关文章:

c# - 如何将整个字符串与正则表达式匹配?

c# - 在gridview中显示数据

c# - 如何将 asp.net web 应用程序连接到 kannel 短信网关?

javascript - 如何使用 JavaScript 将 JSON 字符串中的键和值添加到 innerHTML 中

Javascript:将值列表转换为对象集

JSON 模式 OneOf 级联

c# - 反序列化引用循环不将数据带入构造函数

c# - 使用批处理文件从命令行调用 C# exe

java - 运行 google place api 时出现 JsonParseException : The JsonDeserializer com. google.gson.DefaultTypeAdapters

c# - 使用 Newtonsoft Json.NET 解析具有名称值对的多维 JSON 数组