Home > Backend Development > C++ > How Can I Deserialize Derived Types in JSON.NET While Preserving Type Information?

How Can I Deserialize Derived Types in JSON.NET While Preserving Type Information?

Mary-Kate Olsen
Release: 2025-01-21 18:46:14
Original
723 people have browsed it

How Can I Deserialize Derived Types in JSON.NET While Preserving Type Information?

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template