6

How can I deserialize this JSON data? The keys "100034" etc. are dynamic in nature.

{
    "users" : {
        "100034" : {
            "name"  : "tom",
            "state" : "WA",
            "id"    : "cedf-c56f-18a4-4b1"
        },
        "10045" : {
            "name"  : "steve",
            "state" : "NY",
            "id"    : "ebb2-92bf-3062-7774"
        },
        "12345" : {
            "name"  : "mike",
            "state" : "MA",
            "id"    : "fb60-b34f-6dc8-aaf7"
        }
    }
}

Is there a way I can directly access each object having name, state and Id?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
user2449952
  • 581
  • 1
  • 7
  • 21

2 Answers2

9

For JSON objects having property names which can vary, you can use a Dictionary<string, T> in place of a regular class, where T is a class representing the item data.

Declare your classes like this:

class RootObject
{
    public Dictionary<string, User> users { get; set; }
}

class User
{
    public string name { get; set; }
    public string state { get; set; }
    public string id { get; set; }
}

Then deserialize like this:

RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);

Demo:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
            ""users"": {
                ""10045"": {
                    ""name"": ""steve"",
                    ""state"": ""NY"",
                    ""id"": ""ebb2-92bf-3062-7774""
                },
                ""12345"": {
                    ""name"": ""mike"",
                    ""state"": ""MA"",
                    ""id"": ""fb60-b34f-6dc8-aaf7""
                },
                ""100034"": {
                    ""name"": ""tom"",
                    ""state"": ""WA"",
                    ""id"": ""cedf-c56f-18a4-4b1""
                }
            }
        }";

        RootObject root = JsonConvert.DeserializeObject<RootObject>(json);

        foreach (string key in root.users.Keys)
        {
            Console.WriteLine("key: " + key);
            User user = root.users[key];
            Console.WriteLine("name: " + user.name);
            Console.WriteLine("state: " + user.state);
            Console.WriteLine("id: " + user.id);
            Console.WriteLine();
        }
    }
}

Output:

key: 10045
name: steve
state: NY
id: ebb2-92bf-3062-7774

key: 12345
name: mike
state: MA
id: fb60-b34f-6dc8-aaf7

key: 100034
name: tom
state: WA
id: cedf-c56f-18a4-4b1
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • as I mentioned earlier keys are dynamic.. how would your solution work in that case ? How would I know what to pass as key ? – user2449952 Jul 16 '14 at 05:34
  • Did you try it? The dictionary handles the dynamic keys during deserialization. It is trivial to discover what the keys are by iterating over the `Keys` collection in the dictionary. I've added a demo to my answer. – Brian Rogers Jul 16 '14 at 05:54
  • @BrianRogers Thanks, Roger it helped me a lot. But can you tell me if we are recieving a response without any Key but has Keys in its inner details. I am unable to find a way. e.g. In my case i am receiving such/same type of response but the response object does not have a Key. So how'll i deserialize it because, the data is coming but after deserializing it, it gives null. (My response object has shape like **{"10101":{"name":"aaa", "desc":"aaa111"},{"20202":{"name":"bbb", "desc":"bbb222"}}}** – Asif Mehmood Mar 07 '16 at 14:40
  • @MalikAsif Post this as a new question so that you can fully describe the issue you are facing. You can link back to this question if you need to provide context. – Brian Rogers Mar 08 '16 at 20:30
  • Thanks @BrianRogers . I have used the Dictionary but not in the Parent model. I have used Dictionary while Sending the Request, then it worked perfectly as the Parent Object in Response did not have any key that was previously creating the problem. Thanks, it has been resolved – Asif Mehmood Mar 09 '16 at 07:09
  • 1
    You saved a lot of life I am sure Brian. thank you :) – arslanaybars May 04 '18 at 13:21
-2
  1. Add a package System.Web.Script.Serialization;

  2. Assuming that your JSON contains List of Internet users I create a class Like this..

    public class internet
    {
       public List<User> Users { get; set; }
    };
    public class User
    {
       public String Name { get; set; }
       public String Id { get; set; }
       public String State { get; set; }
    };
    

Assuming that your JSON String is in the variable 'JSONDATA' follow the below code for DE serialize your JSON data to Class objects.

     var JSONDATA = /* Your JSON String */;
     JavaScriptSerializer serializer = new JavaScriptSerializer();
     internet Intr = serializer.Deserialize<internet>(JSONDATA);
Uthaiah
  • 1,283
  • 13
  • 14