Home >Backend Development >C++ >How can I deserialize JSON with dynamic key names in C#?

How can I deserialize JSON with dynamic key names in C#?

DDD
DDDOriginal
2025-01-07 12:41:45491browse

How can I deserialize JSON with dynamic key names in C#?

Deserializing Child Objects with Dynamic Key Names

Introduction

Serializing JSON data with varying key names poses a challenge in deserialization. This article explores a solution using a dynamic property pattern in C#.

Problem Statement

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"
        }
    }
}

Solution

Dynamic Property Pattern

We can represent the varying keys using a Dictionary where T is a class containing the child object data. In this case, we declare 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; }
}

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 property named users populated with the deserialized child objects.

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
}

Demo

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();
        }
    }
}

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

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!

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