Home >Backend Development >C++ >How to Deserialize JSON with Dynamically Named Child Objects in C#?
JSON deserialization of dynamically named sub-objects in C#
Handling deserialization of JSON structures with dynamically named sub-objects can be challenging. Consider the following JSON example:
<code class="language-json">{ "users": { "parentname": "test", "100034": { "name": "tom", "state": "WA", "id": "cedf-c56f-18a4-4b1" }, "10045": { "name": "steve", "state": "NY", "id": "ebb2-92bf-3062-7774" }, "12345": { "name": "mike", "state": "MA", "id": "fb60-b34f-6dc8-aaf7" } } }</code>
Attempts to deserialize using the following code may fail:
<code class="language-csharp">public class RootObject { public string ParentName { get; set; } public Dictionary<string, User> users { get; set; } } public class User { public string name { get; set; } public string state { get; set; } public string id { get; set; } }</code>
This is because RootObject
the known property names in the class do not match the dynamic names of the child objects in the JSON.
The solution is to use a custom converter to handle the dynamic property names and deserialize them into a dictionary of strongly typed objects. To do this, you need:
Create a converter class that inherits from JsonConverter
and provide deserialization and serialization logic:
<code class="language-csharp"> public class TypedExtensionDataConverter<T> : JsonConverter // ... 实现略 ...</code>
Use the [JsonTypedExtensionData]
attribute to mark the attribute in the data model that will hold the dictionary of dynamically named objects:
<code class="language-csharp"> [JsonConverter(typeof(TypedExtensionDataConverter<User>))] class Users { [JsonProperty("parentname")] public string ParentName { get; set; } [JsonTypedExtensionData] public Dictionary<string, User> UserTable { get; set; } }</code>
Updated data model to correctly handle dynamic sub-objects:
<code class="language-csharp"> public class RootObject { [JsonProperty("users")] public Users Users { get; set; } }</code>
By using a custom converter, JSON structures can be successfully deserialized into a strongly typed C# object model, thus preserving the hierarchical structure and dynamic nature of the original data.
The above is the detailed content of How to Deserialize JSON with Dynamically Named Child Objects in C#?. For more information, please follow other related articles on the PHP Chinese website!