Home >Backend Development >C++ >How to Deserialize Polymorphic JSON in Json.NET without Type Information?

How to Deserialize Polymorphic JSON in Json.NET without Type Information?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-02-02 11:51:09377browse

How to Deserialize Polymorphic JSON in Json.NET without Type Information?

No type of information, using json.net back -sequentialized polymorphic JSON class

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!

Statement:
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