json 在c#中反序列化riot champion API

uinbv5nw  于 2022-12-15  发布在  C#
关注(0)|答案(1)|浏览(153)

我正在尝试反序列化防暴冠军API http://ddragon.leagueoflegends.com/cdn/12.23.1/data/en_US/champion.json
但我的冠军DTO仍然是空的。
请帮帮我...

//this is in main page and Constants.chamAPI is the link above with the string type

championDTO = await restService.GetChampData(Constants.champAPi);
 
// this is for Deserialize the JSON file 
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();
            championDTO = JsonConvert.DeserializeObject<RootChampionDTO>(query);
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine("\t\tERROR {0}", ex.Message);
    }

    return championDTO;
}

// this is the class for storing the data from json file.
 
namespace FinalProject
{
    public class RootChampionDTO {
        public List<Champion> Data { get; set; }
    }
    
    public class Champion
    {
        [JsonProperty("id")]
        public int Id { get; set; }
        [JsonProperty("key")]
        public string Key { get; set; }
        [JsonProperty("name")]
        public string Name { get; set; }
        [JsonProperty("title")]
        public string Title { get; set; }
    }
}

我试过Dictionary<string, Champion> data {get; set;},但还是不行。

cwtwac6a

cwtwac6a1#

如果你只需要数据,你必须解析json并反序列化数据。

Dictionary<string,Champion> champions = JObject.Parse(json)["data"]
                                         .ToObject<Dictionary<string,Champion>>();

并且必须修复Champion类的“id”属性,它应该是字符串

public class Champion
{
    [JsonProperty("id")]
    public string Id { get; set; }
    //..... other properties
}


也可以将数据转换为列表

List<Champion> champions =  ((JObject) JObject.Parse(json)["data"]).Properties()
                                      .Select(p=>p.Value.ToObject<Champion>()).ToList();

相关问题