-1

Please help me to parse array from this json in C#:

{
        "error_code":0,
        "response":
        {
            "17":
                {
                    "id":"17","name":"Books"
                },
            "21":
                {
                    "id":"21","name":"Movies"
                },
            "13":
                {
                    "id":"13","name":"Cafe"
                },
            "5":
                {
                    "id":"5","name":"Music"
                },
            "49":
                {
                    "id":"49","name":"Theatres"
                }
        }
    }

I'm using the Newtonsoft.Json library

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
dvlpr
  • 11
  • 4
  • That is not an array, its an object which properties are named with strings which happens to be numbers. – Jite Jul 20 '15 at 13:02

1 Answers1

1

That's not a JSON array - it's just a JSON object which happens to have numbers for the properties of the response object.

You can parse it as a JObject, or deserialize it to a class like this:

public class Root
{
    public int ErrorCode { get; set; }
    public Dictionary<string, Entry> Response { get; set; }
}

public class Entry
{
    public string Id { get; set; }
    public string Name { get; set; }
}

...

Root root = JsonConvert.DeserializeObject<Root>(json);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks, Jon! When I renamed the ErrorCode to "error_code" and Entries to "response" in Root class, then it worked! – dvlpr Jul 20 '15 at 13:12
  • @dvlpr: `Entries` should have been `Response`, but that should be all you need - I'd expect Json.NET to map error_code to ErrorCode. If it doesn't, you can always apply appropriate naming attributes. – Jon Skeet Jul 20 '15 at 13:19