C#反序列化Riot Champion API时championDTO为空问题求助
解决Riot Champion API反序列化后championDTO为空的问题
问题根源及修正步骤:
1. 反序列化对象错误(核心问题)
你的GetChampData方法中,直接将API链接字符串(query)传给了JsonConvert.DeserializeObject,而非API返回的JSON响应内容,这会导致反序列化完全失败,返回null。
修正后的GetChampData方法:
public async Task<RootChampionDTO> GetChampData(string query) { RootChampionDTO championDTO = null; try { var response = await _client.GetAsync(query); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); // 读取API返回的JSON内容 championDTO = JsonConvert.DeserializeObject<RootChampionDTO>(content); // 用JSON内容反序列化 } } catch (Exception ex) { Debug.WriteLine("\t\tERROR {0}", ex.Message); } return championDTO; }
2. DTO类结构与API返回不匹配
Riot Champion API返回的data字段是字典类型(键为英雄ID字符串,值为英雄对象),而非List;同时英雄的id字段是字符串类型(如"Aatrox"),不是int,类型不匹配会导致反序列化失败。
修正后的DTO类:
namespace FinalProject { public class RootChampionDTO { [JsonProperty("data")] // 匹配API返回的小写"data"字段 public Dictionary<string, Champion> Data { get; set; } } public class Champion { [JsonProperty("id")] public string Id { get; set; } // 改为string类型,匹配API返回的字符串ID [JsonProperty("key")] public string Key { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("title")] public string Title { get; set; } } }
验证说明
完成上述修正后,调用restService.GetChampData(Constants.champAPi)就能正确反序列化API返回的英雄数据,championDTO不再为空。
内容的提问来源于stack exchange,提问作者Sean Moon
相关产品推荐
相关产品推荐

