Home > Backend Development > C++ > How to Deserialize Polymorphic JSON Data Using a Custom JSON.NET Converter?

How to Deserialize Polymorphic JSON Data Using a Custom JSON.NET Converter?

Barbara Streisand
Release: 2025-02-02 08:41:08
Original
378 people have browsed it

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>
Copy after login
Now, suppose we have an example of Employee and Artist.

<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>
Copy after login
How do we sequence this JSON to

and correctly identify the specific type of everyone? List<Person>

Custom converter solution

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>
Copy after login

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>
Copy after login
will analyze JSON content to determine the correct type of each person, and create an instance of

,

or
<code class="language-csharp">string json = "[...]"; //  此处应替换为实际的JSON字符串
List<Person> persons = JsonConvert.DeserializeObject<List<Person>>(json, new PersonConverter());</code>
Copy after login
accordingly. This allows seamlessly deepen the polymorphic data structure.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template