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.
You need to do two things
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();
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;
}
var companyTickers = JsonSerializer.Deserialize<Dictionary<int, CompanyTickers>>(json);
foreach(var company in companyTickers.Values)
{
Console.WriteLine($"{company.Cik} {company.Ticker} {company.Title}");
}