Alex Rivera | Logout

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

Asked 2011-06-14T18:26:29.570
78

given this JSON:

[
  {
    "$id": "1",
    "$type": "MyAssembly.ClassA, MyAssembly",
    "Email": "me@here.com",
  },
  {
    "$id": "2",
    "$type": "MyAssembly.ClassB, MyAssembly",
    "Email": "me@here.com",
  }
]

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.

Edit
Report

1 Answer

105

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": "me@here.com",
    },
    {
      "$id": "2",
      "$type": "MyAssembly.ClassB, MyAssembly",
      "Email": "me@here.com",
    }
  ]
}

Then you can deserialize it:

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

Documentation: TypeNameHandling setting

answered 2011-06-27T15:34:28.513

Your Answer