When working with JSON data containing objects with dynamic key names, it becomes challenging to directly access object properties. This is because typical object serialization requires predefined class properties.
To overcome this, we can utilize 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; } }
Using the above classes and the given JSON data:
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
We can now access and iterate over the deserialized objects:
foreach (string key in root.users.Keys) { User user = root.users[key]; // Access user properties here }
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
By leveraging dictionaries, we can effectively deserialize JSON data with dynamic key names and access object properties conveniently.
The above is the detailed content of How to Deserialize JSON with Dynamic Keys Using Dictionaries in C#?. For more information, please follow other related articles on the PHP Chinese website!