Home >Backend Development >C++ >How to Deserialize JSON into an `IEnumerable` using Newtonsoft JSON.NET?

How to Deserialize JSON into an `IEnumerable` using Newtonsoft JSON.NET?

Linda Hamilton
Linda HamiltonOriginal
2025-01-17 13:48:11921browse

How to Deserialize JSON into an `IEnumerable` using Newtonsoft JSON.NET?

Use Newtonsoft JSON.NET to deserialize JSON to IEnumerable

Assume that JSON represents a list of objects with polymorphic types:

<code>[
  {
    "$id": "1",
    "$type": "MyAssembly.ClassA, MyAssembly",
    "Email": "[email protected]"
  },
  {
    "$id": "2",
    "$type": "MyAssembly.ClassB, MyAssembly",
    "Email": "[email protected]"
  }
]</code>

and abstract base and derived classes:

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

Deserialize JSON to IEnumerable

To deserialize JSON to IEnumerable, follow these steps:

  1. Enable TypeNameHandling: Set the TypeNameHandling of JsonSerializerSettings to All to include type information in the deserialized JSON.

    <code> JsonSerializerSettings settings = new JsonSerializerSettings
     {
         TypeNameHandling = TypeNameHandling.All
     };</code>
  2. Serialized JSON: Serializes a list of objects using configured settings.

    <code> string strJson = JsonConvert.SerializeObject(instance, settings);</code>
  3. Modified JSON: The serialized JSON will contain $type information, and the generated JSON will look like this:

    <code> {
       "$type": "System.Collections.Generic.List`1[[MyAssembly.BaseClass, MyAssembly]], mscorlib",
       "$values": [
         {
           "$id": "1",
           "$type": "MyAssembly.ClassA, MyAssembly",
           "Email": "[email protected]"
         },
         {
           "$id": "2",
           "$type": "MyAssembly.ClassB, MyAssembly",
           "Email": "[email protected]"
         }
       ]
     }</code>
  4. Deserialize JSON: Deserialize modified JSON to base class using settings with TypeNameHandling enabled.

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

By following these steps, you can successfully deserialize JSON to IEnumerable, including objects with polymorphic types.

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