Home > Backend Development > C++ > How to Serialize and Deserialize Derived Types in C# with Json.net?

How to Serialize and Deserialize Derived Types in C# with Json.net?

Mary-Kate Olsen
Release: 2025-01-21 18:41:08
Original
658 people have browsed it

How to Serialize and Deserialize Derived Types in C# with Json.net?

Serialize and deserialize derived types using Json.net

Json.net (Newtonsoft) requires special handling to properly serialize and deserialize derived types when using polymorphic inheritance in C#. This article explores how to do this by enabling type name handling.

Question

Consider the following class hierarchy:

<code class="language-csharp">public class Base
{
    public string Name;
}
public class Derived : Base
{
    public string Something;
}</code>
Copy after login

Now, if you try to deserialize a JSON string containing a list of Base objects, but it actually contains Derived objects, you will not be able to recover the derived type information. How to solve this problem?

Answer

Json.net provides the TypeNameHandling option, which enables serialization and deserialization of type names. To use this feature:

  1. Create a JsonSerializerSettings object and set TypeNameHandling to TypeNameHandling.All.
  2. Pass this settings object as a parameter to the SerializeObject and DeserializeObject methods.

Here is an example:

<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

This approach ensures that Json.net preserves type information during serialization and restores it during deserialization, allowing derived types to be restored correctly.

The above is the detailed content of How to Serialize and Deserialize Derived Types in C# with Json.net?. 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