Home >Backend Development >C++ >How can I deserialize JSON with dynamic key names in C#?
Serializing JSON data with varying key names poses a challenge in deserialization. This article explores a solution using a dynamic property pattern in C#.
Considering the JSON data below, how can we deserialize it while maintaining the dynamic "numeric" keys?
{ "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" } } }
Dynamic Property Pattern
We can represent the varying keys using a Dictionary
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; } }
Deserialization
To deserialize the JSON using the dynamic property pattern, we use the following code:
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
This creates an instance of RootObject, with a Dictionary
Accessing Object Data
Now, we can access each child object using their respective keys by iterating over the users dictionary:
foreach (string key in root.users.Keys) { User user = root.users[key]; // Access user properties using user.name, user.state, user.id }
The following C# code demonstrates the entire process:
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); // Iterate over users and print their data foreach (string key in root.users.Keys) { User user = root.users[key]; Console.WriteLine("key: " + key); Console.WriteLine("name: " + user.name); Console.WriteLine("state: " + user.state); Console.WriteLine("id: " + user.id); Console.WriteLine(); } } }
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 I deserialize JSON with dynamic key names in C#?. For more information, please follow other related articles on the PHP Chinese website!