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
DDDOriginal
2025-01-17 13:36:09950browse

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>

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>

When trying to deserialize JSON to:

<code>IEnumerable<基类> deserialized;</code>

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>

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>

Deserialization now performs correctly after including type information:

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

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!

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