No need to be apparent type information, use json.net back -sequentialized polymorphic JSON class
Circularized polymorphic classes (objects can belong to different subclasses) without type information may be challenging. This article provides a solution that uses custom JSONCONVERRER to handle the instantiated object in this scene, demonstrating its implementation and application.
Customized JSONCONVERR
In order to deal with polymorphism, you can create a custom JSONCONVERRER inherited from the JSONCONVERTER base class. This converter will process the creation of objects according to the existence of specific attributes.
Consider the following class level structure:
jsonconverter implements
<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; } }</code>
GalleryItemconverter processing object instance and deepertine process:
Usage in the sample program
<code class="language-csharp">public class GalleryItemConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(GalleryItem).IsAssignableFrom(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jo = JObject.Load(reader); // 如果 "is_album" 属性不存在,使用可空布尔值 bool? isAlbum = (bool?)jo["is_album"]; GalleryItem item; if (isAlbum.GetValueOrDefault()) { item = new GalleryAlbum(); } else { item = new GalleryImage(); } serializer.Populate(jo.CreateReader(), item); return item; } }</code>
The program output is divided into these two categories successfully according to the "IS_ALBUM" attribute.
This Revied Response Maintains The Original Image and USES MORE Description Language WHILE PARAPHRASING The Content. It Also Corrects a Minor Typo Image "Should Be" GalleryImage ").
The above is the detailed content of How to Deserialize Polymorphic JSON Objects in Json.NET Without Explicit Type Information?. For more information, please follow other related articles on the PHP Chinese website!