When dealing with polymorphic types in JSON.NET, when the type is not clearly defined in JSON, the JSON data back -sequentialization backbone type object may be challenging. This guide demonstrates how to achieve custom JSONCONVERRER to overcome this obstacle.
Challenge
Consider the following JSON data:
The task is to return this JSON data to
, where[ { "Department": "Department1", "JobTitle": "JobTitle1", "FirstName": "FirstName1", "LastName": "LastName1" }, { "Department": "Department2", "JobTitle": "JobTitle2", "FirstName": "FirstName2", "LastName": "LastName2" }, { "Skill": "Painter", "FirstName": "FirstName3", "LastName": "LastName3" } ]
and List<Person>
are derived classes. Person
Employee
<决> Solution Artist
In order to deal with this situation, we will create a custom class called , which inherits
. Class is a custom converter used when the type of the values that infer the values of the back -sequentialization from the JSON data. PersonConverter
JsonConverter
JsonCreationConverter<Person>
JsonCreationConverter<T>
public class PersonConverter : JsonCreationConverter<Person> { protected override Person Create(Type objectType, JObject jObject) { if (FieldExists("Skill", jObject)) { return new Artist(); } else if (FieldExists("Department", jObject)) { return new Employee(); } else { return new Person(); } } private bool FieldExists(string fieldName, JObject jObject) { return jObject[fieldName] != null; } }
method is rewritten to perform the following steps:
Read JSON data into. PersonConverter
ReadJson
Call the method to determine the type according to the JSON attribute.
JObject
Back to the newly created object. Create
Use the converter JsonSerializer.Populate
To use a custom converter, you can use the following code: By achieving custom , you can handle polymorphic derivatives in json.net. The provided in this guide demonstrates how to analyze JSON data and determine the appropriate derived type. This method can flexibly handle polymorphism during the deepertine.
The above is the detailed content of How to Implement a Custom JsonConverter in JSON.NET for Polymorphic Deserialization?. For more information, please follow other related articles on the PHP Chinese website!