Using a custom json.net converter back -sequentialized polymorphic JSON data
Custom JSON.NET converter provides a powerful mechanism to customize serialization and back -sequentialization process. It allows developers to expand the function of JSON.NET to process more complicated data types or scenarios.
When such a scene appears when dealing with polymorphism, different types of inheritance of inheritance. Consider the following example:
<code class="language-csharp">public class Person { public string FirstName { get; set; } public string LastName { get; set; } } public class Employee : Person { public string Department { get; set; } public string JobTitle { get; set; } } public class Artist : Person { public string Skill { get; set; } }</code>
<code class="language-json">[ { "Department": "Department1", "JobTitle": "JobTitle1", "FirstName": "FirstName1", "LastName": "LastName1" }, { "Department": "Department2", "JobTitle": "JobTitle2", "FirstName": "FirstName2", "LastName": "LastName2" }, { "Skill": "Painter", "FirstName": "FirstName3", "LastName": "LastName3" } ]</code>
and correctly identify the specific type of everyone? List<Person>
Standard does not provide a method based on JSON content to determine the correct type. However, we can rewrite the method and introduce a new abstract
method (this method accepts a) to create our own custom converter: CustomCreationConverter
ReadJson
Create
In our specific scene, we created a expansion JObject
<code class="language-csharp">public abstract class JsonCreationConverter<T> : JsonConverter { protected abstract T Create(Type objectType, JObject jObject); public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jObject = JObject.Load(reader); T target = Create(objectType, jObject); serializer.Populate(jObject.CreateReader(), target); return target; } }</code>
JsonCreationConverter<Person>
Using this custom converter, we can deepen the JSON string: PersonConverter
<code class="language-csharp">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; } }</code>
,
or<code class="language-csharp">string json = "[...]"; // 此处应替换为实际的JSON字符串 List<Person> persons = JsonConvert.DeserializeObject<List<Person>>(json, new PersonConverter());</code>
PersonConverter
Employee
The above is the detailed content of How to Deserialize Polymorphic JSON Data Using a Custom JSON.NET Converter?. For more information, please follow other related articles on the PHP Chinese website!