Json.net derived type deserialization
When processing JSON data, it can be advantageous to serialize and deserialize objects that follow a base-derived class relationship. However, Json.net (Newtonsoft) requires specific configuration to handle derived types efficiently.
Question:
Consider the following base and derived classes:
<code>public class Base { public string Name; } public class Derived : Base { public string Something; }</code>
If you try to deserialize a JSON string containing base and derived class objects to List<Base>
, you will only get the base class object, thus losing the derived type information.
Solution:
To successfully deserialize derived types, you need to enable type name handling. This can be achieved by creating a JsonSerializerSettings
object and setting the TypeNameHandling
property to All
. Pass this settings object to serialization and deserialization operations:
<code>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>
By enabling type name handling, Json.net will include type information in the JSON string. During deserialization, it will use this information to correctly recreate the derived object and populate deserializedList
.
Note: Using this method exposes the names of all objects as well as the list itself in the serialized data. If this is a problem, consider alternative ways of handling polymorphic relationships.
The above is the detailed content of How Can I Deserialize Derived Types in JSON.NET While Preserving Type Information?. For more information, please follow other related articles on the PHP Chinese website!