Home >Backend Development >C++ >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>
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>
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>
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>
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!