Home > Backend Development > C++ > How to Deserialize JSON into an IEnumerable with Newtonsoft JSON.NET when BaseType is Abstract?

How to Deserialize JSON into an IEnumerable with Newtonsoft JSON.NET when BaseType is Abstract?

DDD
Release: 2025-01-17 13:36:09
Original
947 people have browsed it

How to Deserialize JSON into an IEnumerable with Newtonsoft JSON.NET when BaseType is Abstract?

Use Newtonsoft JSON.NET to deserialize JSON to IEnumerable

When BaseType is an abstract class, it can be challenging to use JsonConvert.Deserialize to deserialize JSON data to IEnumerable.

Question:

Consider the following JSON:

<code>[
  {
    "$id": "1",
    "$type": "MyAssembly.ClassA, MyAssembly",
    "Email": "[email\u00a0protected]"
  },
  {
    "$id": "2",
    "$type": "MyAssembly.ClassB, MyAssembly",
    "Email": "[email\u00a0protected]"
  }
]</code>
Copy after login

and the following abstract base and derived classes:

<code>public abstract class BaseClass
{
    public string Email;
}
public class ClassA : BaseClass
{
}
public class ClassB : BaseClass
{
}</code>
Copy after login

When trying to deserialize JSON to:

<code>IEnumerable<基类> deserialized;</code>
Copy after login

When using JsonConvert.Deserialize>(), you will encounter errors because BaseClass is abstract.

Solution:

To solve this problem, use the TypeNameHandling setting in JsonSerializerSettings. By setting this setting to TypeNameHandling.All, type information will be included in the deserialized JSON.

<code>JsonSerializerSettings settings = new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
};

string strJson = JsonConvert.SerializeObject(instance, settings);</code>
Copy after login

Updated JSON:

<code>{
  "$type": "System.Collections.Generic.List`1[[MyAssembly.BaseClass, MyAssembly]], mscorlib",
  "$values": [
    {
      "$id": "1",
      "$type": "MyAssembly.ClassA, MyAssembly",
      "Email": "[email\u00a0protected]",
    },
    {
      "$id": "2",
      "$type": "MyAssembly.ClassB, MyAssembly",
      "Email": "[email\u00a0protected]",
    }
  ]
}</code>
Copy after login

Deserialization now performs correctly after including type information:

<code>IEnumerable<BaseClass> obj = JsonConvert.DeserializeObject<IEnumerable<BaseClass>>(strJson, settings);</code>
Copy after login

The above is the detailed content of How to Deserialize JSON into an IEnumerable with Newtonsoft JSON.NET when BaseType is Abstract?. 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