Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to deserialize JSON into IEnumerable<BaseType> with Newtonsoft JSON.NET

Tags:

c#

json.net

given this JSON:

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

and these classes:

public abstract class BaseClass {     public string Email; } public class ClassA : BaseClass { } public class ClassB : BaseClass { } 

How can I deserialize the JSON into:

IEnumerable<BaseClass> deserialized; 

I can't use JsonConvert.Deserialize<IEnumerable<BaseClass>>() because it complains that BaseClass is abstract.

like image 246
Andrew Bullock Avatar asked Jun 14 '11 18:06

Andrew Bullock


1 Answers

You need:

JsonSerializerSettings settings = new JsonSerializerSettings {     TypeNameHandling = TypeNameHandling.All };  string strJson = JsonConvert.SerializeObject(instance, settings); 

So the JSON looks like this:

{   "$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]",     }   ] } 

Then you can deserialize it:

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

Documentation: TypeNameHandling setting

like image 127
Andrew Bullock Avatar answered Sep 21 '22 09:09

Andrew Bullock