如何将指定JSON反序列化为List?反序列化遇System.NullReferenceException
问题解决步骤
核心问题分析
- API返回的JSON根字段是
chart,但你的Root类定义的是coins,反序列化后data.coins会是null,这就是NullReferenceException的直接原因。 - JSON里的
chart是二维数值数组,每个子数组的第一个元素是时间戳,第二个是价格,和你定义的Coin类结构不匹配,无法直接反序列化为List<Coin>。
修正后的代码
1. 调整类结构与反序列化逻辑
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; class Program { // 复用HttpClient,避免频繁创建 private static readonly HttpClient _httpClient = new HttpClient(); static async Task Main(string[] args) { await Content(); Console.ReadKey(); } private static async Task Content() { List<Coin> coins = await CallApiAsync(); foreach (var coin in coins) { Console.WriteLine($"时间戳: {coin.Time}, 价格: {coin.Price}"); } } static async Task<List<Coin>> CallApiAsync() { string url = "https://api.coinstats.app/public/v1/charts?period=all&coinId=bitcoin"; var httpResponse = await _httpClient.GetAsync(url); // 确保请求成功,避免无效JSON导致的问题 httpResponse.EnsureSuccessStatusCode(); string jsonResponse = await httpResponse.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject<Root>(jsonResponse); // 将二维数组转换为Coin对象列表 List<Coin> coins = new List<Coin>(); foreach (var item in data.Chart) { coins.Add(new Coin { Time = (long)item[0], // 时间戳数值较大,用long避免溢出 Price = (decimal)item[1] // 价格是小数,用decimal保证精度 }); } return coins; } } public class Root { // 字段名和JSON里的"chart"对应,注意大小写(Newtonsoft默认驼峰匹配) public List<object[]> Chart { get; set; } } public class Coin { public long Time { get; set; } public decimal Price { get; set; } }
关键修改点说明
- 把
Root类的coins字段改为Chart,和JSON的根字段名匹配。 - 将
Chart的类型定义为List<object[]>,匹配JSON里的二维数组结构。 - 手动遍历二维数组,将每个子数组的元素映射到
Coin对象的属性上,同时修正类型:时间戳用long避免溢出,价格用decimal保留精度。 - 将
Main和Content方法改为async Task,避免async void带来的潜在问题。 - 复用
HttpClient实例,符合.NET最佳实践。 - 添加
httpResponse.EnsureSuccessStatusCode(),确保请求失败时直接抛出异常,便于排查问题。
内容的提问来源于stack exchange,提问作者vajuakos
相关产品推荐
相关产品推荐

