我正在尝试反序列化暴乱冠军API http://ddragon.leagueoflegends.com/cdn/12.23.1/data/en_US/champion.json
但是我仍然得到null在我的冠军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("ttERROR {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;}
这还是不行
如果只需要数据,则必须解析json并对数据进行反序列化。你可以使用Dictionary
Dictionary<string,Champion> champions = JObject.Parse(json)["data"]
.ToObject<Dictionary<string,Champion>>();
,你必须修改"id"属性,它应该是一个字符串
public class Champion
{
[JsonProperty("id")]
public string Id { get; set; }
//..... other properties
}
或者可以将数据转换为List
List<Champion> champions = ((JObject) JObject.Parse(json)["data"]).Properties()
.Select(p=>p.Value.ToObject<Champion>()).ToList();