Turning return Json into object list C #

2

I have a request for an API that returns me the following JSON:

{"champions":[{"id":266,"active":true,"botEnabled":false,"freeToPlay":true,"botMmEnabled":false,"rankedPlayEnabled":true},{"id":201,"active":true,"botEnabled":false,"freeToPlay":true,"botMmEnabled":false,"rankedPlayEnabled":true},{"id":51,"active":true,"botEnabled":true,"freeToPlay":true,"botMmEnabled":true,"rankedPlayEnabled":true},{"id":86,"active":true,"botEnabled":true,"freeToPlay":true,"botMmEnabled":true,"rankedPlayEnabled":true},{"id":74,"active":true,"botEnabled":false,"freeToPlay":true,"botMmEnabled":false,"rankedPlayEnabled":true},{"id":222,"active":true,"botEnabled":false,"freeToPlay":true,"botMmEnabled":false,"rankedPlayEnabled":true},{"id":55,"active":true,"botEnabled":false,"freeToPlay":true,"botMmEnabled":false,"rankedPlayEnabled":true},{"id":64,"active":true,"botEnabled":false,"freeToPlay":true,"botMmEnabled":false,"rankedPlayEnabled":true},{"id":111,"active":true,"botEnabled":false,"freeToPlay":true,"botMmEnabled":false,"rankedPlayEnabled":true},{"id":76,"active":true,"botEnabled":true,"freeToPlay":true,"botMmEnabled":true,"rankedPlayEnabled":true},{"id":112,"active":true,"botEnabled":false,"freeToPlay":true,"botMmEnabled":false,"rankedPlayEnabled":true}]}

I have the following class:

public class Champions
{
    public int Id { get; set; }

    public bool BotEnabled { get; set; }
}

How do I make the Json return into a List<Champions> ?

    
asked by anonymous 03.03.2016 / 17:16

2 answers

1

You can do the following.

public class ChampionsList
{
    public List<Champions> Champions { get; set; }  
}

public class Champions
{
    [JsonProperty(PropertyName = "Id")]
    public string Id { get; set; }
    [JsonProperty(PropertyName = "BotEnabled")]
    public bool BotEnabled { get; set; }
}

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod()]
public void LoadChampions(String RespJson)
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    try
    {
        var ChampionsList = js.Deserialize<ChampionsList>(RespJson);

        foreach (var c in ChampionsList.Champions)
        {
        }
    }
    catch (Exception exe)
    {
    }
}
    
03.03.2016 / 17:24
1

You can use the Newtonsoft DLL to try this:

public IEnumerable<Champions> LoadChampions(string json)
{ 
  return JsonConvert.DeserializeObject<IEnumerable<Champions>>(json);
}
    
03.03.2016 / 17:37