Home >Backend Development >C++ >How to Deserialize Polymorphic JSON Without Type Information Using JSON.NET?
No need type information is required to use json.net back -sequentialized polymorphic JSON class
JSON.NET is a powerful .NET JSON serialization and desertileization library. However, when there is no type of information in the serialized data, the counter -sequential polymorphism JSON may be challenging.
Question: Lack of type information
Polymorphism allows multiple classes to inherit from a public base class. When the deepericularization represents the JSON data of the polymorphic object, if there is no type of information, it is difficult to determine which class should be instantiated.
For example, considering the following JSON data, it indicates that Gallery Image or Gallery Album class:
"IS_ALBUM" attributes are distinguished. The "IS_ALBUM" of Gallery Images is set to false, and Gallery Albums is set to true.
<code class="language-json">{ "id": "OUHDm", "title": "My most recent drawing. Spent over 100 hours.", "is_album": false }</code>Solution: Jsonconveter
For the dependentization of this polymorphic JSON, you can create a custom JSONCONVERRER to process the object instance. The converter checks the "IS_ALBUM" property and create the corresponding class instance. This is a sample converter called GalleryitemConverter:
<code class="language-csharp">public class GalleryItemConverter : JsonConverter { // 指定转换器可以转换GalleryItem及其派生类 public override bool CanConvert(Type objectType) => typeof(GalleryItem).IsAssignableFrom(objectType); public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // 将JSON读取为JObject 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(); // 从JSON数据填充项目属性 serializer.Populate(jo.CreateReader(), item); return item; } }</code>To use the converter, please include it as a parameter in the default json.net backlier serializer, as shown below:
Example output
Using the JSON data and custom converter provided, you can get the deserted GalleryItem object:
<code class="language-csharp">var items = JsonConvert.DeserializeObject<List<GalleryItem>>(json, new GalleryItemConverter());</code>
The above is the detailed content of How to Deserialize Polymorphic JSON Without Type Information Using JSON.NET?. For more information, please follow other related articles on the PHP Chinese website!