Deserializing derived types using Json.net
Suppose you have a base class Base
and a derived class Derived
, where Derived
inherits from Base
. You have a list of Base
objects, which contains instances of Base
and Derived
. When you deserialize the JSON representation of this list, you want to retrieve the derived type as its actual type, not just as a Base
object.
To achieve this, Json.net provides a feature called Type name handling. By enabling this feature and passing it as a settings parameter to the serialization and deserialization operations, you can specify the object type that should be included in the serialized JSON.
<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>
is deserialized, deserializedList
will contain Base
and Derived
objects of the correct type. However, enabling type name handling has a drawback: it will include the names of all objects and lists in the serialized JSON, which may not be ideal in some cases.
The above is the detailed content of How Can I Deserialize a List of Base and Derived Types Using Json.net and Preserve Their Actual Types?. For more information, please follow other related articles on the PHP Chinese website!