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

C#中List<CompanyTicker> JSON反序列化失败求助

问题分析与解决方法

问题场景

从SEC API获取到的JSON结构如下(键为数字字符串的对象,而非数组):

{"0":{"cik_str":789019,"ticker":"MSFT","title":"MICROSOFT CORP"},"1":{"cik_str":320193,"ticker":"AAPL","title":"Apple Inc."},"2":{"cik_str":1045810,"ticker":"NVDA","title":"NVIDIA CORP"},"3":{"cik_str":1652044,"ticker":"GOOGL","title":"Alphabet Inc."},"4":{"cik_str":1018724,"ticker":"AMZN","title":"AMAZON COM INC"},"5":{"cik_str":1326801,"ticker":"META","title":"Meta Platforms, Inc."},"6":{"cik_str":1067983,"ticker":"BRK-B","title":"BERKSHIRE HATHAWAY INC"}}

尝试将其反序列化为List<CompanyTicker>时抛出异常,错误提示:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[StockDataUtilities.DataStructures.CompanyTicker]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path '0', line 1, position 5.

错误原因

List<T>类型对应JSON中的数组结构(用[]包裹),但当前返回的JSON是对象结构(用{}包裹,键为数字字符串,值为公司数据对象),类型不匹配导致反序列化失败。

解决方法

方法一:先反序列化为字典,再转为列表

修改GetCompanyTickers方法,先将JSON反序列化为Dictionary<string, CompanyTicker>,再提取字典的值转为List<CompanyTicker>:

#region Get Company Tickers
public static List<CompanyTicker> GetCompanyTickers()
{
    // 先反序列化为字典
    var tickerDict = GetValue<Dictionary<string, CompanyTicker>>(companyTickers);
    // 提取字典的值转为列表
    return tickerDict.Values.ToList();
}
#endregion

GetValue<T>方法无需修改,因为Dictionary<string, CompanyTicker>是符合JSON对象结构的.NET类型。

方法二:自定义JSON转换器(适用于需要直接反序列化为列表的场景)

如果希望保持GetValue<List<CompanyTicker>>的调用方式,可以自定义一个JsonConverter来处理这种对象转列表的逻辑:

public class ObjectToListConverter<T> : JsonConverter<List<T>>
{
    public override List<T> ReadJson(JsonReader reader, Type objectType, List<T> existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        // 将JSON对象转为JObject,再提取所有值并转为T类型的列表
        var jObject = JObject.Load(reader);
        return jObject.Properties().Select(p => p.Value.ToObject<T>()).ToList();
    }

    public override void WriteJson(JsonWriter writer, List<T> value, JsonSerializer serializer)
    {
        // 如果需要序列化列表为这种对象结构,可以在这里实现,否则抛出异常
        throw new NotImplementedException();
    }
}

然后修改GetValue方法中的反序列化代码,传入转换器:

var value = JsonConvert.DeserializeObject<T>(json, new ObjectToListConverter<CompanyTicker>());

代码验证

两种方法都能正确将返回的JSON转换为List<CompanyTicker>,方法一更简单直接,适合大多数场景;方法二更灵活,适合需要复用转换逻辑的场景。

内容的提问来源于stack exchange,提问作者SoggyCoder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:05:32