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

如何在C#中序列化GitHub ExchangeApi返回的动态JSON数据

C# 反序列化无固定结构键值对JSON的正确实现

问题背景

项目中使用ExchangeApi,该API返回无固定结构的键值对JSON(例如货币代码与对应名称的映射),为避免为每个货币单独编写属性,最初尝试通过包含Dictionary<string, string>的DTO类进行反序列化,但未成功。

失败原因分析

最初的DTO类将字典包装在CountryCurrencys属性中,但API返回的JSON本身是顶级键值对结构,并非嵌套在CountryCurrencys字段下,因此反序列化时无法匹配对应属性,导致失败。

失败代码示例

调用代码

public async static void GetCurrencies()
{
    HttpResponseMessage response = await _client.GetAsync(currenciesUrl);
    response.EnsureSuccessStatusCode();
    var jsonReponse = await response.Content.ReadAsStringAsync();
    var test = JsonSerializer.Deserialize<CountriesCurrencyListDTO>(jsonReponse);
}

对应的DTO类

public class CountriesCurrencyListDTO
{
    public Dictionary<string, string> CountryCurrencys { get; set; }
}

正确实现方式

直接将JSON反序列化为Dictionary<string, string>类型,无需额外DTO包装,同时增加请求失败的降级处理:

public async static void GetCurrencies()
{
    HttpResponseMessage response = await _client.GetAsync(currenciesUrl);
    if (!response.IsSuccessStatusCode)
    {
        response = await _client.GetAsync(currenciesFallbackUrl);
    }

    var jsonReponse = await response.Content.ReadAsStringAsync();
    var test = JsonSerializer.Deserialize<Dictionary<string,string>>(jsonReponse);

    string testQuery = "Mexican Peso";
    string testQuery2 = "Bitcoin";
    if (test != null)
    {
        foreach (var currency in test)
        {
            if (currency.Value.Equals(testQuery) || currency.Value.Equals(testQuery2)){
                Console.WriteLine("HI");
            }
        }
    }
}

核心要点:

  • 用Dictionary<string, string>直接匹配API返回的顶级键值对JSON结构
  • 新增fallback请求逻辑,提升接口调用可靠性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 20:52:28