Home >Backend Development >C++ >How Can Json.net Handle Serializing and Deserializing Derived Types?

How Can Json.net Handle Serializing and Deserializing Derived Types?

Barbara Streisand
Barbara StreisandOriginal
2025-01-21 18:28:10947browse

How Can Json.net Handle Serializing and Deserializing Derived Types?

Serialization and deserialization of derived types in Json.NET (Newtonsoft)

Json.NET provides flexibility in serializing and deserializing complex data structures. When dealing with derived types, it is crucial to preserve type information during serialization so that it deserializes correctly.

Json.NET implements this functionality through the JsonSerializerSettings attribute of the TypeNameHandling object. By setting this property to All, Json.NET will include the type name in the serialized output.

For example, consider the following base and derived classes:

<code class="language-csharp">public class Base
{
    public string Name;
}

public class Derived : Base
{
    public string Something;
}</code>

To serialize and deserialize derived types:

<code class="language-csharp">// 序列化
var object1 = new Base() { Name = "Object1" };
var object2 = new Derived() { Something = "Some other thing" };
var inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string serialized = JsonConvert.SerializeObject(inheritanceList, settings);

// 反序列化
var deserializedList = JsonConvert.DeserializeObject<List<Base>>(serialized, settings);</code>

With this approach, Json.NET preserves type information, allowing derived types to be successfully deserialized. However, it is important to note that the serialized output will contain the types associated with the objects and any lists used to hold them.

The above is the detailed content of How Can Json.net Handle Serializing and Deserializing Derived Types?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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