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

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

DDD
Release: 2025-01-17 10:17:09
Original
859 people have browsed it

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 present challenges when deserializing into objects. Here's how to solve this problem using dictionary methods.

For example, consider the following JSON string:

<code>{
    "daily": {
        "1337990400000": 443447,
        "1338076800000": 444693,
        "1338163200000": 452282,
        "1338249600000": 462189,
        "1338336000000": 466626
    }
}</code>
Copy after login

Since the keys are dynamic, using a JavascriptSerializer with a class structure is not sufficient 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.

<code class="language-csharp">var deser = new JavaScriptSerializer().Deserialize<Dictionary<string, Dictionary<string, int>>>(val);</code>
Copy after login

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

To access specific data we can use the following code:

<code class="language-csharp">var justDaily = deser["daily"];</code>
Copy after login

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

<code class="language-csharp">foreach (string key in justDaily.Keys)
    Console.WriteLine(key + ": " + justDaily[key]);</code>
Copy after login

This approach allows us to handle JSON strings with dynamic root keys by converting them into dictionary structures and provides flexibility when accessing the data. You can take full advantage of the power of dictionaries to easily deserialize JSON even if the keys are unpredictable.

The above is the detailed content of How to Deserialize JSON with Dynamic Keys Using a Dictionary 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template