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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:01:01