JSON反序列化异常:instrumentProfile字段为null求助
问题分析与解决
核心问题有两个:
- 键名拼写不匹配:JSON里的字段是
instumentProfile(缺少字母r),而你的类属性名是instrumentProfile(带有r)。Json.NET默认按属性名和JSON键名严格匹配,所以无法正确映射,导致instrumentProfile为null。 - 数据结构不匹配:JSON中
instumentProfile的日期字段对应的直接是数值数组(比如[50.0,...]),但你的类里定义的是Dictionary<string, VWInstrumentProfile>,期望每个日期对应一个包含Strikes属性的对象,结构完全不对应。
解决方案
方案1:调整类结构匹配JSON(推荐)
直接把instrumentProfile的类型改成Dictionary<string, List<double>>,同时用JsonProperty特性修正键名映射:
public class JsonParsedData { public string Asset { get; set; } // 用JsonProperty指定JSON中的键名,同时类型改为List<double>匹配JSON数组 [JsonProperty("instumentProfile")] public Dictionary<string, List<double>> InstrumentProfile { get; set; } }
方案2:修改JSON结构匹配类定义
如果必须保留VWInstrumentProfile类,需要把JSON中日期对应的数组包装成对象:
[{"asset":"AAPL","instumentProfile":{"2023-06-30":{"Strikes":[50.0,...]},...}}]
同时给类属性加上JsonProperty修正拼写:
public class VWInstrumentProfile { public List<double> Strikes { get; set; } } public class JsonParsedData { public string Asset { get; set; } [JsonProperty("instumentProfile")] public Dictionary<string, VWInstrumentProfile> InstrumentProfile { get; set; } }
额外优化:简化解析代码
原代码里的两次JObject.Parse完全冗余,直接反序列化即可:
for (int i = 0; i < jsonArray.Count; i++) { JsonParsedData data = JsonConvert.DeserializeObject<JsonParsedData>(jsonArray[i].ToString()); Console.WriteLine("Asset: " + data.Asset); if (data.InstrumentProfile != null) { foreach (var profile in data.InstrumentProfile) { Console.WriteLine("Date: " + profile.Key); } } }
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

