如何在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
相关产品推荐
相关产品推荐

