Kragalon
Kragalon

Reputation: 440

C# deserialize nested lists and foreach them

I'm wanting to run a foreach loop through a nested List in this JSON.

I'm getting some JSON that looks like:

{
    "name":"Placeholder",
    "entries":
        [
            {
                "playerId": "27271906",
                "playerName": "Billy"
            },
            {
                "playerId": "35568613",
                "playerName": "Jeeves"
            }
        ]
}

Classes:

public class IDs
{
    public string playerId { get; set; }
}

public class Top
{
    public List<IDs> entries { get; set; }
}

When I go to run the program, it seems to not work when it gets to:

List<string> pros = new List<string>();
using (var web = new WebClient())
{
    web.Encoding = System.Text.Encoding.UTF8;
    var jsonString = responseFromServer;
    var jss = new JavaScriptSerializer();
    var ProsList = jss.Deserialize<List<IDs>>(jsonString);
    int i = 1;

    foreach (IDs x in ProsList)
    {                        
        pros.Add(x.playerId);
        i++;
        if (i == 3)
        {
            break;
        }
    }
}

When I have it set up like this, it will say that I can't use a foreach since there's no enumerator. Any idea? I'm new to C# and this syntax, so it may be really easy for some people to see. Thanks!

I would add that I'm using Visual Studio 2013.

Upvotes: 0

Views: 1119

Answers (1)

ekad
ekad

Reputation: 14614

You have to deserialize the json into Top instead of List<IDs>, and enumerate result.entries. Change your code to below

List<string> pros = new List<string>();
using (var web = new WebClient())
{
    web.Encoding = System.Text.Encoding.UTF8;
    var jsonString = responseFromServer;
    var jss = new JavaScriptSerializer();
    var result = jss.Deserialize<Top>(jsonString);
    int i = 1;

    foreach (IDs x in result.entries)
    {                        
        pros.Add(x.playerId);
        i++;
        if (i == 3)
        {
            break;
        }
    }
}

Alternatively you can also use JSON.NET like below

List<string> pros = new List<string>();
using (var web = new WebClient())
{
    web.Encoding = System.Text.Encoding.UTF8;
    var jsonString = responseFromServer;

    var result = JsonConvert.DeserializeObject<Top>(jsonString);
    int i = 1;

    foreach (IDs x in result.entries)
    {                        
        pros.Add(x.playerId);
        i++;
        if (i == 3)
        {
            break;
        }
    }
}

Working demo: https://dotnetfiddle.net/naqPx2

Upvotes: 1

Related Questions