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

C#使用JsonConvert解析Coincap API JSON提取ID列表失败求助

解析Coincap API JSON数据提取ID字段的问题

我刚开始学习C#,尝试调用https://api.coincap.io/v2/assets接口获取JSON数据,想要将数据中的id字段提取到List<string>中,但始终无法成功解析数据。以下是API返回的JSON示例和我编写的代码,希望有人能指出我代码中的错误:

API返回JSON示例

{"data":[{"id":"bitcoin","rank":"1","symbol":"BTC","name":"Bitcoin","supply":"19231150.0000000000000000","maxSupply":"21000000.0000000000000000","marketCapUsd":"329260408122.7321099930951000","volumeUsd24Hr":"4938807092.4540332151393315","priceUsd":"17121.2022225780626740","changePercent24Hr":"-0.1557069639360563","vwap24Hr":"17167.6185642050963449","explorer":"https://blockchain.info/"},{"id":"ethereum","rank":"2","symbol":"ETH","name":"Ethereum","supply":"122373866.2178000000000000","maxSupply":null,"marketCapUsd":"154858258278.7620692762684030","volumeUsd24Hr":"1556598691.7310630183480862","priceUsd":"1265.4520369826888988","changePercent24Hr":"-0.3774876415990869","vwap24Hr":"1271.6091894467065872","explorer":"https://etherscan.io/"},{"id":"tether","rank":"3","symbol":"USDT","name":"Tether","supply":"65708194111.5796100000000000","maxSupply":null,"marketCapUsd":"65788824004.4908415146900527","volumeUsd24Hr":"6971097526.7488883793650250","priceUsd":"1.0012270903804526","changePercent24Hr":"0.0236756537376818","vwap24Hr":"1.0002996279301237","explorer":"https://www.omniexplorer.info/asset/31"}],"timestamp":1670800790134}

我的代码

public class Coins
{
    public Dictionary<string, ListDictionary> data { get; set; }
}

public class Program
{
    static void Main(string[] args)
    { 
        List<string> coin_list = new List<string>();

        HttpClient Client = new HttpClient();

        string URL = "https://api.coincap.io/v2/";

        string response = Client.GetStringAsync(URL + "assets").Result; 
        
        Coins list = JsonConvert.DeserializeObject<Coins>(response);

        foreach(item in list.data)
        {
             coin_list.add(item.id);
        }

        Console.ReadLine();
    }
}

代码中的错误及修正方案

1. 实体类结构不匹配JSON

API返回的data是对象数组,但你定义的Coins类中data字段类型为Dictionary<string, ListDictionary>,完全不符合JSON结构。需要重新定义实体类匹配层级:

// 对应整个JSON响应
public class CoinsResponse
{
    public List<CoinItem> data { get; set; }
    public long timestamp { get; set; } // 匹配JSON中的时间戳字段
}

// 对应data数组中的单个对象
public class CoinItem
{
    public string id { get; set; } // 仅保留需要提取的id字段,其他字段可按需添加
}

2. foreach循环语法错误

  • 未指定item的类型,C#中需显式声明或用var推断类型
  • 原list.data是Dictionary类型,遍历逻辑错误;修正后应遍历List<CoinItem>集合

3. 方法名大小写错误

C#是大小写敏感语言,coin_list.add需改为coin_list.Add

4. HttpClient使用不规范

直接用.Result阻塞调用可能导致死锁,建议使用async/await;同时用using包裹HttpClient确保资源正常释放


修正后的完整代码

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

public class CoinsResponse
{
    public List<CoinItem> data { get; set; }
    public long timestamp { get; set; }
}

public class CoinItem
{
    public string id { get; set; }
}

public class Program
{
    static async Task Main(string[] args)
    { 
        List<string> coin_list = new List<string>();

        using HttpClient client = new HttpClient();
        string url = "https://api.coincap.io/v2/assets";

        string response = await client.GetStringAsync(url); 
        CoinsResponse result = JsonConvert.DeserializeObject<CoinsResponse>(response);

        // 空值检查避免空引用异常
        if (result?.data != null)
        {
            foreach (var item in result.data)
            {
                coin_list.Add(item.id);
            }
        }

        // 输出测试提取的id
        foreach (var id in coin_list)
        {
            Console.WriteLine(id);
        }

        Console.ReadLine();
    }
}

内容的提问来源于stack exchange,提问作者Vilenzo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:25:26