C# Json List<object> Deserialization Error

Advertisements

I’m trying to access company ticker data using the SEC’s API. I’m able to retrieve the JSON string which looks like this:

{"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"}}

I want to deserialize this list as a list of CompanyTicker objects.
Here is the main code:

#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

And here is the CompanyTicker class:

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

I end up getting an exception thrown here:
var value = JsonConvert.DeserializeObject<T>(json);

The error message says:
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.

I’m new to API calling and utilizing Json, and I’m not sure what could be wrong. The json string format seems to be correct for a list of objects, but maybe I’m missing something. Any help that could be provided will be greatly appreciated.

I’ve tried storing it as a single object which stores a list of CompanyTicker objects, and I’ve tried storing it as a single object. I didn’t really expect those to work, but I’m not sure what else I should be trying.

>Solution :

The JSON you’ve provided fundamentally doesn’t represent a list. It’s a JSON object. You can deserialize that into a Dictionary<int, CompanyTicker> and then convert that that to a list though, treating it as a sequence of key/value pairs:

var tickers = JsonConvert.DeserializeObject<Dictionary<int, CompanyTicker>>(json)
    .OrderBy(pair => pair.Key)
    .Select(pair => pair.Value)
    .ToList();

Leave a ReplyCancel reply