0

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.

ekad
  • 14,436
  • 26
  • 44
  • 46
Kragalon
  • 420
  • 1
  • 6
  • 25
  • possible duplicate of [Deserialize JSON into C# dynamic object?](http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – Kutyel Dec 05 '14 at 07:34
  • I think it's more about the `foreach` enumeration, idk though. – Kragalon Dec 05 '14 at 11:59

1 Answers1

1

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

ekad
  • 14,436
  • 26
  • 44
  • 46