Search code examples
c#jsondotnet-httpclient

In .NET Core: how to read a json response as list


I need help to read a Json response with no item's list like a list, using HttpClient.

In particular I want to read this object like a list:

{
    "0": {
        "cik_str": 320193,
        "ticker": "AAPL",
        "title": "Apple Inc."
    },
    "1": {
        "cik_str": 789019,
        "ticker": "MSFT",
        "title": "MICROSOFT CORP"
    },
    "2": {
        "cik_str": 1067983,
        "ticker": "BRK-B",
        "title": "BERKSHIRE HATHAWAY INC"
    }
}

The full response is in here: www.sec.gov/files/company_tickers.json

I need a code example.

Thanks in advance.


Solution

  • You need to do two things

    1. Load your Jason from server
    var url = "https://www.sec.gov/files/company_tickers.json";
    var client = new HttpClient();
    var response = await client.GetAsync(url);
    if (!response.IsSuccessStatusCode)
    {
        Console.WriteLine($"Error: Can not connect with the server {response.StatusCode}");
        return;
    }
    var json = await response.Content.ReadAsStringAsync();
    
    1. Deserialize your JSON
    • add the following class to your project
    public class CompanyTickers
    {
        [JsonPropertyName("cik_str")]
        public int Cik{ get; set; }
        [JsonPropertyName("ticker")]
        public string Ticker { get; set; } = string.Empty;
        [JsonPropertyName("title")]
        public string Title { get; set; } = string.Empty;
    }
    
    • DeSerialize and use your results
    var companyTickers = JsonSerializer.Deserialize<Dictionary<int, CompanyTickers>>(json);
    foreach(var company in companyTickers.Values)
    {
        Console.WriteLine($"{company.Cik} {company.Ticker} {company.Title}");
    }