"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to use dictionary deserialization of JSON with dynamic keys in C#

How to use dictionary deserialization of JSON with dynamic keys in C#

Posted on 2025-05-03
Browse:450

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

Flexible handling of JSON deserialization with dynamic keys using dictionaries

In the JSON world, encountering JSON strings with dynamic and unpredictable root keys can pose challenges when deserialized to objects. Here is how to solve this problem using a dictionary method.

For example, consider the following JSON string:

{
    "daily": {
        "1337990400000": 443447,
        "1338076800000": 444693,
        "1338163200000": 452282,
        "1338249600000": 462189,
        "1338336000000": 466626
    }
}

Since the keys are dynamic, using JavascriptSerializer with class structure is not enough here. A more flexible solution is to deserialize the JSON string into a dictionary, which allows us to easily access dynamic keys and their corresponding values.

var deser = new JavaScriptSerializer().Deserialize>>(val);

This line creates a dictionary deser where the key is a string and the value is a dictionary with string keys and integer values. It effectively maps dynamic keys in JSON strings to intermediate dictionaries.

To access specific data, we can use the following code:

var justDaily = deser["daily"];
The

justDaily variable now contains a dictionary representing a "daily" object from a JSON string. We can iterate over its keys and values ​​to extract dynamic keys and corresponding values.

foreach (string key in justDaily.Keys)
    Console.WriteLine(key   ": "   justDaily[key]);

This approach allows us to process JSON strings with dynamic root keys to dictionary structures and provide flexibility when accessing data. Even if the keys are unpredictable, it is possible to take advantage of the dictionary's capabilities to easily deserialize JSON.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3