Home >Backend Development >C++ >How to Deserialize JSON into an `IEnumerable` using Newtonsoft JSON.NET?
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>
To deserialize JSON to IEnumerable
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>
Serialized JSON: Serializes a list of objects using configured settings.
<code> string strJson = JsonConvert.SerializeObject(instance, settings);</code>
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>
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
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!