Home >Backend Development >C++ >How to Deserialize Polymorphic JSON in Json.NET without Type Information?
When the JSON data contains different types of objects and does not have an explicit type information, JSON.NET's back -serialization will face challenges. In order to overcome this obstacle, a custom JSONCONVERTER can be developed, which instantly instantiated the corresponding class according to specific attributes.
Let's consider an example, where the IMGUR API calls returns a list, which contains the GalleryImage and Galleryalbum classes expressed in JSON. Due to the lack of $ Type attributes, it is not feasible to use JSON.NET for automation. However, by using the IS_ALBUM property, we can distinguish these two categories.
To realize custom JSONCONVERTER, we define our class and create a GalleryItemconVerter, as shown below:
In the ReadJson method of the converter, we check the IS_ALBUM property to determine the type of object to be instantiated. Then use a serializer to fill the JSON data into the object.
<code class="language-csharp">public abstract class GalleryItem { public string id { get; set; } public string title { get; set; } public string link { get; set; } public bool is_album { get; set; } } public class GalleryImage : GalleryItem { // ... } public class GalleryAlbum : GalleryItem { public int images_count { get; set; } public List<GalleryImage> images { get; set; } } public class GalleryItemConverter : JsonConverter { // ... }</code>
This is an example program that demonstrates the usage of this converter:
The output displayed the object of the deepertization and its respective attributes, including the image of the Galleryalbum object. The custom GalleryItemconVerter provides a solution that can be serialized without an explicit type information to effectively handle various data structures.
<code class="language-csharp">List<GalleryItem> items = JsonConvert.DeserializeObject<List<GalleryItem>>(json, new GalleryItemConverter());</code>
The above is the detailed content of How to Deserialize Polymorphic JSON in Json.NET without Type Information?. For more information, please follow other related articles on the PHP Chinese website!