Transform Json return to list of C#objects

Asked

Viewed 1,086 times

2

I have a request for an API that returns 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 turn the return Json into a List<Champions> ?

  • Managed? .......

  • The class should be called Champion and not Champions.

  • For this change being that the return is as champions ?

  • @Jonathanbarcela Some answer below solved your problem?

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)
    {
    }
}
  • 1

    You are setting up an empty list, and in Json you have 11 objects.

  • I changed the answer

1

You can use the dll Newtonsoft tries so:

public IEnumerable<Champions> LoadChampions(string json)
{ 
  return JsonConvert.DeserializeObject<IEnumerable<Champions>>(json);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.