You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 16:31:02