简体   繁体   中英

How do i get multiple single objects in a json converted into a C# object list?

Im trying to make a program using the League of legends API. The API doesnt return a array of objects. It has different objects for each champions. My question is, how can i get these objects into ac# list without having to make a object for each champion in C#? https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?api_key=362039df-6ce4-4e2f-ac3c-27d246d03f45 (This is the json list im getting) I have the following code to convert the objects, but obviously it cannot fill the list.

var webclient = new WebClient();
var strJson = webclient.DownloadString("https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?api_key=362039df-6ce4-4e2f-ac3c-27d246d03f45");
var List<ChampionJson> = JsonConvert.DeserializeObjectList<<ChampionJson>>(strJson);

This is the champion class:

public class ChampionJson
{
    public Champion champion { 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 know its probably completely wrong what im doing but im pretty new to Json. I have been trying to get it to work the past two days but i cannot find anything on the internet. Pls help, Thanks in advance!

Your object basically needs to reflect the model the JSON is providing. You are quite close; I would change the ChampionJson object definition to:

public class ChampionJson { public Dictionary<string, Champion> data { get; set; } }

and then use

JsonConvert.DeserializeObject<ChampionJson>(strJson) 

instead of

JsonConvert.DeserializeObjectList<<ChampionJson>>(strJson)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM