.NET Core中使用HttpClient将无列表结构JSON响应转为列表
使用HttpClient读取键值对JSON并转换为列表
目标JSON以数字字符串为键、公司信息对象为值,可通过以下步骤将其转换为列表:
- 定义匹配JSON结构的模型类:对应每个公司的信息字段
- 使用HttpClient发起请求:注意SEC要求的请求头标识
- 反序列化为字典:将JSON解析为键值对集合
- 提取字典值转为列表:获取所有公司信息对象组成的列表
代码示例(使用System.Text.Json)
using System; using System.Collections.Generic; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; using System.Linq; class Program { private static readonly HttpClient _httpClient = new HttpClient(); static async Task Main(string[] args) { try { // SEC API要求必须设置User-Agent,替换为你的应用信息和邮箱 _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Your-App-Name/1.0 (your-email@example.com)"); string jsonUrl = "https://www.sec.gov/files/company_tickers.json"; var response = await _httpClient.GetAsync(jsonUrl); response.EnsureSuccessStatusCode(); // 抛出请求失败的异常 string jsonContent = await response.Content.ReadAsStringAsync(); // 反序列化为字典,键是数字字符串,值是CompanyInfo对象 var companyDictionary = JsonSerializer.Deserialize<Dictionary<string, CompanyInfo>>(jsonContent); // 将字典中的所有值提取为列表 var companyList = new List<CompanyInfo>(companyDictionary.Values); // 示例:输出前5条数据 foreach (var company in companyList.Take(5)) { Console.WriteLine($"CIK: {company.CikStr}, 股票代码: {company.Ticker}, 公司名称: {company.Title}"); } } catch (HttpRequestException ex) { Console.WriteLine($"请求失败: {ex.Message}"); } catch (JsonException ex) { Console.WriteLine($"JSON解析错误: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"发生未知错误: {ex.Message}"); } } } // 模型类:匹配JSON中的字段名 public class CompanyInfo { [JsonPropertyName("cik_str")] public long CikStr { get; set; } [JsonPropertyName("ticker")] public string Ticker { get; set; } [JsonPropertyName("title")] public string Title { get; set; } }
可选:使用Newtonsoft.Json的版本
如果习惯使用Newtonsoft.Json,需先通过NuGet安装Newtonsoft.Json包,代码调整如下:
修改模型类
using Newtonsoft.Json; public class CompanyInfo { [JsonProperty("cik_str")] public long CikStr { get; set; } [JsonProperty("ticker")] public string Ticker { get; set; } [JsonProperty("title")] public string Title { get; set; } }
修改反序列化代码
// 替换System.Text.Json的反序列化行 var companyDictionary = JsonConvert.DeserializeObject<Dictionary<string, CompanyInfo>>(jsonContent);
注意事项
- 必须设置合法的
User-Agent请求头,否则SEC服务器会返回403禁止访问。 - 建议复用
HttpClient实例,避免频繁创建导致的资源浪费。
内容的提问来源于stack exchange,提问作者TempestOwl
相关产品推荐
相关产品推荐

