Home >Backend Development >C++ >How to Deserialize JSON with Dynamic Keys Using Dictionaries in C#?

How to Deserialize JSON with Dynamic Keys Using Dictionaries in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-07 12:47:411033browse

How to Deserialize JSON with Dynamic Keys Using Dictionaries in C#?

Deserialize JSON with Dynamic Keys Using Dictionaries

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 structure, where string represents the dynamic key names, and T is the class holding the object data. This approach allows for flexible deserialization of objects with varying properties.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn