在 .NET Core 中:如何将 json 响应读取为列表

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

我需要帮助来读取没有像列表一样的项目列表的 Json 响应,使用

HttpClient

特别是我想像列表一样读取这个对象:

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

完整回复在这里:www.sec.gov/files/company_tickers.json

我需要一个代码示例。

提前致谢。

c# json dotnet-httpclient
1个回答
0
投票

你需要做两件事

  1. 从服务器加载你的 Jason
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. 反序列化您的 JSON 将以下类添加到您的项目中
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}");
}
© www.soinside.com 2019 - 2024. All rights reserved.