You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:43:01