7

I am using data from an external API that returns JSON such as the following.

{
  "data": {
    "4": {
      "id": "12",
      "email": "q23rfedsafsadf",
      "first_name": "lachlan",

Using JSON.NET, how do I get the 4 value? This is dynamic as it changes for each record (not the most ideal API I've ever used).

Lock
  • 5,422
  • 14
  • 66
  • 113
  • 4
    Deserialize to a dictionary for your `data` field values as is shown in [Deserialize nested JSON into C# objects](http://stackoverflow.com/a/38793347/3744182) or [Create a strongly typed c# object from json object with ID as the name](http://stackoverflow.com/a/34213724/3744182). – dbc Dec 29 '16 at 22:14

1 Answers1

20

Here's a working dotNetFiddle: https://dotnetfiddle.net/6Zq5Ry

Here's the code:

using System;
using Newtonsoft.Json;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string json = @"{
                      'data': {
                        '4': {
                          'id': '12',
                          'email': 'lachlan12@somedomain.com',
                          'first_name': 'lachlan'
                          },
                        '5': {
                          'id': '15',
                          'email': 'appuswamy15email@somedomain.com',
                          'first_name': 'appuswamy'
                          }
                       }
                    }";

        var data = JsonConvert.DeserializeObject<RootObject>(json);
        Console.WriteLine("# of items deserialized : {0}", data.DataItems.Count);
        foreach ( var item in data.DataItems)
        {
            Console.WriteLine("  Item Key {0}: ", item.Key);
            Console.WriteLine("    id: {0}", item.Value.id);
            Console.WriteLine("    email: {0}", item.Value.email);
            Console.WriteLine("    first_name: {0}", item.Value.first_name);
        }
    }
}

public class RootObject
{
    [JsonProperty(PropertyName = "data")]
    public Dictionary<string,DataItem> DataItems { get; set; }
}

public class DataItem
{
    public string id { get; set; }
    public string email { get; set; }
    public string first_name { get; set; }
}

Here's the output:

enter image description here

Shiva
  • 20,575
  • 14
  • 82
  • 112