Deserialize riot champion api in c#

145 views Asked by At

I am trying deserialize riot champion API http://ddragon.leagueoflegends.com/cdn/12.23.1/data/en_US/champion.json

but I am still getting null in my championDTO...

Please help me...

//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; }
    }
}

I tried Dictionary<string, Champion> data {get; set;} and this is still not working.

1

There are 1 answers

0
Serge On

if you need only data , you have to parse the json and deserialize data. You can use Dictionary

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

and you have to fix "id" property of Champion class, it should be a string

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

or you can convert data to List

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