【问题标题】:Converting Json that returns multiple class types in c#在c#中转换返回多种类类型的Json
【发布时间】:2019-12-16 12:58:54
【问题描述】:

所以我已经为自己开始了一个项目,我正在使用 AlphaVantage API(https://www.alphavantage.co/documentation/) 但是我遇到了一个问题,他们返回一个大致如下结构的对象:

{[Meta Data, {{
  "1. Information": "Weekly Prices (open, high, low, close) and Volumes",
  "2. Symbol": "ko",
  "3. Last Refreshed": "2019-12-13",
  "4. Time Zone": "US/Eastern"
}}]}
{[Weekly Time Series, {{
  "2019-12-13": {
    "1. open": "54.3000",
    "2. high": "54.5500",
    "3. low": "53.6600",
    "4. close": "54.4200",
    "5. volume": "54644469"
  },
  "2019-12-13": {
    "1. open": "54.3000",
    "2. high": "54.5500",
    "3. low": "53.6600",
    "4. close": "54.4200",
    "5. volume": "54644469"
  }
}}]}

这将被构造为两个独立的对象,如下所示:

public class MetaData
{
    public string Information { get; set; }
    public string Symbol { get; set; }
    public DateTime LastRefresh { get; set; }
    public String TimeZone { get; set; }
}
public class Data
{
    public List<ValueData> entry { get; set; }
}
public class ValueData
{
    public DateTime Date { get; set; }
    public decimal Open { get; set; }
    public decimal High { get; set; }
    public decimal Low { get; set; }
    public decimal Close { get; set; }
    public int Volume { get; set; }
}

我的问题是反序列化的最佳做法是什么?我尝试只对一个对象类型这样做,并用调试器检查它,它包含 2 个独立的结构。

【问题讨论】:

  • 这是有效的 Json 吗?
  • 不,不是@geo
  • 但似乎 OP 有一个复制/粘贴错误,调用 alphavantage.co/… 显示我有效的 Json
  • @MindSwipe 是的。那么这不能反序列化。 bailey-dunn 共享一个有效的 JSON。
  • 作为替代方案,似乎有一个现成可用的库:github.com/LutsenkoKirill/AlphaVantage.Net(未测试)

标签: c# json json-deserialization


【解决方案1】:

在 C# 中,有多种方法可以将 JSON 反序列化为对象。最流行的是Newtonsoft.Json,也称为Json.NET,然后您可以使用.NET Core 3.0 中的System.Text.Json API。以下是两者的示例:

Json.NET

var obj = JsonConvert.DeserializeObject<Type>(jsonString);

Type 是您的基础基类型(它似乎只是一个包含 Meta DataWeekly Time Series 的属性的类),jsonString 是您下载的 JSON。 Alphavantage 在其属性名称中使用空格,因此您需要使用 JsonPropertyAttribute 属性并指定名称

或者 .NET Core 3:

var obj = JsonSerializer.Parse<Type>(jsonString);

Type 再次是您的基础基类型,您需要再次使用属性来正确映射属性,但这次您需要 JsonPropertyNameAttribute

但是,如果您不想自己创建和测试类,您可以查看Alphavantage.Net,虽然未经测试,但可以为您节省大量时间。向 Christoph Lütjen 大喊以将其链接到 cmets

【讨论】:

  • 感谢您的帮助。我目前正在为此使用 newtonsoft 库。但是,如果您查看元数据的右括号,它实际上是发送了两个不同结构的独立对象。所以我的问题是我不知道如何反序列化为两个不同的对象。我尝试反序列化为包含每个类的类,它只返回 null。
  • @BaileyDunn 您复制到问题中的 JSON 也是无效的,缺少逗号、缺少引号并且您有 2 个根对象,请编辑您的问题并将 JSON 更新为您的实际 JSON跨度>
猜你喜欢
  • 1970-01-01
  • 2016-09-09
  • 2021-04-13
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-05
相关资源
最近更新 更多