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

How Can I Deserialize JSON with Dynamic Keys in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-17 10:27:09561browse

How Can I Deserialize JSON with Dynamic Keys in C#?

Handling JSON deserialization of dynamic keys in C#

When processing JSON data, encountering dynamic keys can cause deserialization challenges. Consider the following JSON string:

<code class="language-json">{
    "daily": {
        "1337990400000": 443447,
        "1338076800000": 444693,
        "1338163200000": 452282,
        "1338249600000": 462189,
        "1338336000000": 466626
    }
}</code>

In this string, the "daily" key is static, but the underlying key is dynamic and cannot be predicted when deserializing. To solve this problem, we can take advantage of the power of dynamic objects.

Using the JavaScriptSerializer class, we can create a dynamic object as shown below:

<code class="language-csharp">dynamic deser = new JavaScriptSerializer().Deserialize<dynamic>(val);</code>

This deserialization will create a dynamic object deser which can access JSON properties. To access daily data we can use the following statement:

<code class="language-csharp">dynamic justDaily = deser["daily"];</code>
The

justDaily object now represents daily data and its dynamic keys can be accessed. To iterate over the keys and their values ​​we can use the following code:

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

This will output the dynamic keys and their corresponding values. By using dynamic objects, we can efficiently deserialize JSON data even when dynamic keys are encountered.

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