反序列化JSON返回空值C#

时间:2019-04-19 14:10:05

标签: c# json serialization deserialization json-deserialization

我想反序列化来自API请求的数据,但是当我尝试反序列化时,它总是返回空值。

这是JSON数据:

{
  "Meta Data": {
    "1. Information": "FX Intraday (1min) Time Series",
    "2. From Symbol": "USD",
    "3. To Symbol": "EUR",
    "4. Last Refreshed": "2019-04-19 09:19:00",
    "5. Interval": "1min",
    "6. Output Size": "Compact",
    "7. Time Zone": "UTC"
  },
  "Time Series FX (1min)": {
    "2019-04-19 09:19:00": {
      "1. open": "0.8890",
      "2. high": "0.8890",
      "3. low": "0.8890",
      "4. close": "0.8890"
    },
    "2019-04-19 09:18:00": {
      "1. open": "0.8890",
      "2. high": "0.8890",
      "3. low": "0.8890",
      "4. close": "0.8890"
    }
  }
}

下面是我尝试对其进行转换的方式:

public class Data
{
    [JsonProperty("Meta Data")]
    public MetaData MetaData { get; set; }
    [JsonProperty("Time Series FX (1min)")]
    public TimeSeries TimeSeries { get; set; }
}

public class MetaData
{
    [JsonProperty("1. Information")]
    public string Information { get; set; }
    [JsonProperty("2. From Symbol")]
    public string FromSymbol { get; set; }
    [JsonProperty("3. To Symbol")]
    public string ToSymbol { get; set; }
    [JsonProperty("4. Last Refreshed")]
    public string LastRefreshed { get; set; }
    [JsonProperty("5. Interval")]
    public string Interval { get; set; }
    [JsonProperty("6. Output Size")]
    public string OutputSize { get; set; }
    [JsonProperty("7. Time Zone")]
    public string TimeZone { get; set; }
}

public class TimeSeries
{
    public List<Time> Times { get; set; }
}

public class Time 
{
    [JsonProperty("1. open")]
    public decimal Open { get; set; }
    [JsonProperty("2. high")]
    public decimal High { get; set; }
    [JsonProperty("3. low")]
    public decimal Low { get; set; }
    [JsonProperty("4. close")]
    public decimal Close { get; set; }
}

现在用数字更新后,元数据将带有适当的值,但是TimeSeries总是给我一个空值。我怀疑我的模型合适,所以请看一下。我哪里出错了?

3 个答案:

答案 0 :(得分:4)

从JSON标识符中删除数字。 如果属性与源代码中编写的属性不完全相同,则JSON.Net将找不到这些属性。

例如:

{ "Information": "myInfo" }

代替:

{ "1. Information": "myInfo" }

答案 1 :(得分:2)

正如SimonC所说,JSON数据与类中的数据不匹配。如果API的返回值是固定的,则您需要:

[JsonProperty("1. Information")]
public string Information { get; set; }

不是

[JsonProperty("Information")]
public string Information { get; set; }

对该类中所有其他属性的JsonProperty属性进行类似的更改

答案 2 :(得分:1)

[JsonProperty("Information")] public string Information { get; set; }中的[JsonProperty("1. Information")] public string Information { get; set; }更改为public class MetaData     老实说,您应该以这种方式更改所有public class MetaData对象!