JSON.NET Customized multi -state objects serialize, no additional type field
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
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
<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
Circularization is dynamically treated, allowing the class structure to modify the class structure in the future without damaging serialization.
It eliminates the redundant$type
in the code fragment, and the implementation of the 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!