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.
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.
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>
The User class remains unchanged.
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>
The UserTable property in the Users object will now contain the deserialized User object, allowing access to its data.
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!