Serialize and deserialize derived types using Json.net
Json.net (Newtonsoft) requires special handling to properly serialize and deserialize derived types when using polymorphic inheritance in C#. This article explores how to do this by enabling type name handling.
Question
Consider the following class hierarchy:
<code class="language-csharp">public class Base { public string Name; } public class Derived : Base { public string Something; }</code>
Now, if you try to deserialize a JSON string containing a list of Base objects, but it actually contains Derived objects, you will not be able to recover the derived type information. How to solve this problem?
Answer
Json.net provides the TypeNameHandling option, which enables serialization and deserialization of type names. To use this feature:
Here is an example:
<code class="language-csharp">// 序列化 Base object1 = new Base() { Name = "Object1" }; Derived object2 = new Derived() { Something = "Some other thing" }; List<Base> inheritanceList = new List<Base>() { object1, object2 }; JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; string Serialized = JsonConvert.SerializeObject(inheritanceList, settings); // 反序列化 List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);</code>
This approach ensures that Json.net preserves type information during serialization and restores it during deserialization, allowing derived types to be restored correctly.
The above is the detailed content of How to Serialize and Deserialize Derived Types in C# with Json.net?. For more information, please follow other related articles on the PHP Chinese website!