When working with JSON data containing objects with dynamic keys, conventional class deserialization can pose challenges. This article will explore how to tackle this scenario using JSON.NET.
Consider the following JSON data:
{ "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" } } }
How can we access each object directly from this data, without the need for manual key parsing?
JSON.NET offers a convenient solution for deserializing objects with dynamic keys using its Dictionary
To achieve this, we define two classes:
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; } }
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);
The following code demonstrates how to access the objects from the deserialized data:
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(); }
The code will produce the following 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
The above is the detailed content of How can JSON.NET efficiently deserialize JSON with dynamic keys into accessible objects?. For more information, please follow other related articles on the PHP Chinese website!