Home > Backend Development > C++ > How to Deserialize Child Objects with Dynamic Numeric Key Names in JSON using Newtonsoft.Json.Net?

How to Deserialize Child Objects with Dynamic Numeric Key Names in JSON using Newtonsoft.Json.Net?

Barbara Streisand
Release: 2025-01-13 19:00:43
Original
203 people have browsed it

How to Deserialize Child Objects with Dynamic Numeric Key Names in JSON using Newtonsoft.Json.Net?

Use Newtonsoft.Json.Net to deserialize sub-objects with dynamic numeric key names

Deserializing JSON data with dynamic key names can be challenging, especially when the keys are numeric. Here's how to solve this problem using Newtonsoft.Json.Net.

The provided JSON structure contains a parent "users" object with known and unknown properties. To accommodate unknown properties, a custom converter is required.

Custom converter

The TypedExtensionDataConverter class is a custom JSON converter that handles the deserialization of objects with dynamic properties. It ensures that unknown properties are deserialized into a typed container, in this case a dictionary of User objects.

The converter uses the JsonTypedExtensionDataAttribute attribute to identify attributes that should contain dynamic data.

Modified class definition

In order to use custom converters, the "Users" and "User" classes were modified to contain properties and converters.

Users class:

<code>[JsonConverter(typeof(TypedExtensionDataConverter<Users>))]
class Users
{
    ...
    [JsonTypedExtensionData]
    public Dictionary<string, User> UserTable { get; set; }
}</code>
Copy after login

The User class remains unchanged.

How to use

Using a custom converter and modified class definition, deserialization can be performed as follows:

<code>string json = @"...与之前相同的 JSON...";

RootObject root = JsonConvert.DeserializeObject<RootObject>(json);</code>
Copy after login

The UserTable property in the Users object will now contain the deserialized User object, allowing access to its data.

Conclusion

By using a custom JSON converter, you can deserialize sub-objects with dynamic numeric key names, allowing you to seamlessly handle complex JSON structures.

The above is the detailed content of How to Deserialize Child Objects with Dynamic Numeric Key Names in JSON using Newtonsoft.Json.Net?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template