为了账号安全,请及时绑定邮箱和手机立即绑定

反序列化 JSON 返回空值 C#

反序列化 JSON 返回空值 C#

C#
largeQ 2022-12-24 09:54:02
我想反序列化来自 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 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

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

例如:

{ "Information": "myInfo" }

代替:

{ "1. Information": "myInfo" }


查看完整回答
反对 回复 2022-12-24
?
开心每一天1111

TA贡献1836条经验 获得超13个赞

正如 SimonC 所说,JSON 数据与您在课堂上拥有的数据不匹配。如果 API 的返回值是固定的,那么您需要:

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

不是

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

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


查看完整回答
反对 回复 2022-12-24
?
翻翻过去那场雪

TA贡献2065条经验 获得超13个赞

把你的[JsonProperty("Information")]    public string Information { get; set; }改成 [JsonProperty("1. Information")]    public string Information { get; set; }你的public class MetaData 老实说,你应该把所有的public class MetaData对象都改成这样!

查看完整回答
反对 回复 2022-12-24
  • 3 回答
  • 0 关注
  • 100 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信