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
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!