Home > Backend Development > C++ > How Can I Deserialize a List of Base and Derived Types Using Json.net and Preserve Their Actual Types?

How Can I Deserialize a List of Base and Derived Types Using Json.net and Preserve Their Actual Types?

DDD
Release: 2025-01-21 18:35:09
Original
862 people have browsed it

How Can I Deserialize a List of Base and Derived Types Using Json.net and Preserve Their Actual Types?

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>
Copy after login
After

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template