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
Release: 2025-01-07 12:47:41
Original
1004 people have browsed it

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; }
}
Copy after login

Using the above classes and the given JSON data:

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

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
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template