Home >Backend Development >C++ >How Can I Achieve Custom Serialization of Polymorphic Child Objects in Json.Net Without the '$type' Field?

How Can I Achieve Custom Serialization of Polymorphic Child Objects in Json.Net Without the '$type' Field?

Linda Hamilton
Linda HamiltonOriginal
2025-01-24 13:12:10237browse

How Can I Achieve Custom Serialization of Polymorphic Child Objects in Json.Net Without the

JSON.NET Customized multi -state objects serialize, no additional type field

Question:

The

setting/inverse -sequentialization of the

setting/derivative of the JSON.NET is very convenient. However, this method will introduce additional TypeNameHandling.Auto fields in the serialized JSON, increasing the overhead. $type

Solution:

Custom base class with coding type attributes:

Instead of stored sub -type information in the container class, it is better to add it as a attribute to the base class:

This attribute reflects the type of the object of the object and encodes it into an enumeration value.

Dictionary needs to be implemented by itself to map the type to enumerated value.
<code class="language-csharp">[JsonConverter(typeof(SubTypeClassConverter))]
public class SubTypeClassBase
{
    [JsonConverter(typeof(StringEnumConverter))]
    public SubType Type { get { return typeToSubType[GetType()]; } }
}</code>

JsonConverter is used for deepense: typeToSubType

Create a custom :

The method needs to be implemented by itself, and returns the corresponding type according to the enumeration value. JsonConverter

Advantages:
<code class="language-csharp">public class SubTypeClassConverter : JsonConverter
{
    // 读取 JSON 并确定实际类型
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        var typeToken = token["Type"];
        var actualType = SubTypeClassBase.GetTypeFromSubType(typeToken.ToObject<SubType>(serializer)); // 使用 GetTypeFromSubType 方法
        if (existingValue == null || existingValue.GetType() != actualType)
        {
            // 创建实际的对象实例
            var contract = serializer.ContractResolver.ResolveContract(actualType);
            existingValue = contract.DefaultCreator();
        }
        // 使用 "Populate" 方法避免无限递归
        using (var subReader = token.CreateReader())
        {
            serializer.Populate(subReader, existingValue);
        }
        return existingValue;
    }

    // ...其他方法 (WriteJson 等) ...
}</code>

GetTypeFromSubType

Sub -type information encoding in the attributes in the class, independent of the container.

Circularization is dynamically treated, allowing the class structure to modify the class structure in the future without damaging serialization.

It eliminates the redundant
    field in the JSON output and reduces its size.
  • Note:
  • The specific implementation of
  • and $type in the code fragment, and the implementation of the
  • method. write.
enumeration should include all possible sub -types.

The dictionary should map the type of each subclass to the corresponding enumeration value. Methods should perform reverse mapping. GetTypeFromSubType

The above is the detailed content of How Can I Achieve Custom Serialization of Polymorphic Child Objects in Json.Net Without the '$type' Field?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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