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

How to Deserialize JSON with Dynamic Keys in C#?

Barbara Streisand
Release: 2025-01-07 12:51:45
Original
269 people have browsed it

How to Deserialize JSON with Dynamic Keys in C#?

Dynamic Keys in JSON Deserialization

When dealing with JSON data containing dynamic keys, accessing object properties can be challenging. Consider the following 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"
        }
    }
}
Copy after login

In this JSON object, the keys are numeric strings, making it difficult to define classes with static property names. To resolve this, we can leverage the Dictionary type in C#, where T represents the class for our item data.

Class Structure and Deserialization

We define the following 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; }
}
Copy after login

Then, we can deserialize the JSON data like so:

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

This creates a RootObject instance with a Dictionary named users.

Accessing Object Properties

We can now access the object properties using the dictionary keys. The following code iterates through the users:

foreach (string key in root.users.Keys)
{
    User user = root.users[key];
    // Access properties using user.name, user.state, etc.
}
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

This approach allows us to deserialize JSON data with dynamic keys and access object properties seamlessly.

The above is the detailed content of How to Deserialize JSON with Dynamic Keys 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