C# Json 列表<object>反序列化错误

问题描述 投票:0回答:1

我正在尝试使用 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"}}

我想将此列表反序列化为 CompanyTicker 对象列表。 主要代码如下:

#region Get Company Tickers
        public static List<CompanyTicker> GetCompanyTickers()
        {
            return GetValue<List<CompanyTicker>>(companyTickers);
        }
        #endregion

        #region Get Value
        private static T GetValue<T>(string path) where T : new()
        {
            try
            {
                using (var request = new HttpRequestMessage(new HttpMethod("GET"), path))
                {
                    request.Headers.TryAddWithoutValidation("User-Agent", email);
                    var response = _httpClient.SendAsync(request).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        var json = response.Content.ReadAsStringAsync().Result;
                        var value = JsonConvert.DeserializeObject<T>(json);
                        return value;
                    }
                    else
                    {
                        string errorToLog = response + " " + response.Content.ReadAsStringAsync().Result;
                        Console.WriteLine(errorToLog);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return new T();
        }
        #endregion

这是 CompanyTicker 类:

public class CompanyTicker
    {
        public int cik_str { get; set; }
        public string ticker { get; set; }
        public string title { get; set; }
    }

我最终在这里抛出了一个异常:

var value = JsonConvert.DeserializeObject<T>(json);

错误消息显示: 无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[StockDataUtilities.DataStructures.CompanyTicker]',因为该类型需要 JSON 数组(例如 [1, 2,3])以正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为正常的 .NET 类型(例如,不是像整数这样的基本类型,不是像这样的集合类型)数组或列表),可以从 JSON 对象反序列化。还可以将 JsonObjectAttribute 添加到类型中以强制其从 JSON 对象反序列化。 路径“0”,第 1 行,位置 5。

我对 API 调用和使用 Json 很陌生,我不确定会出现什么问题。 json 字符串格式对于对象列表似乎是正确的,但也许我遗漏了一些东西。任何可以提供的帮助将不胜感激。

我尝试将其存储为单个对象,该对象存储 CompanyTicker 对象列表,并且我尝试将其存储为单个对象。我真的没想到这些会起作用,但我不确定我还应该尝试什么。

c# json serialization
1个回答
1
投票

您提供的 JSON 基本上不代表列表。它是一个 JSON 对象。您可以将其反序列化为

Dictionary<int, CompanyTicker>
,然后将其转换为列表,将其视为键/值对序列:

var tickers = JsonConvert.DeserializeObject<Dictionary<int, CompanyTicker>>(json)
    .OrderBy(pair => pair.Key)
    .Select(pair => pair.Value)
    .ToList();
© www.soinside.com 2019 - 2024. All rights reserved.