Implement customized JSONCONVERRTER
Let's consider an example, where you have a base class Person and two derived Employee and Artist. You have a list of Person objects that need to be serialized as JSON. However, you want to avoid using TypenameHandling. This is where the custom JSONCONVERTER can play a role.
For this reason, we need to define a custom converter PersonConverter, which expands the JSONCREATIONVERter
. In the Create method of the converter, we can analyze the JSON object to determine the correct derivative type according to the existence of specific fields.
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; } }
object, you can use a custom converter:
string json = "[...]"; List<Person> persons = JsonConvert.DeserializeObject<List<Person>>(json, new PersonConverter());
The above is the detailed content of How to Create a Custom JsonConverter in JSON.NET to Handle Polymorphic Serialization without TypeNameHandling?. For more information, please follow other related articles on the PHP Chinese website!