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

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


Here is a way to do it without populating $type in the json.

A Json Converter:

public class FooConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(BaseFoo));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        if (jo["FooBarBuzz"].Value<string>() == "A")
            return jo.ToObject<AFoo>(serializer);

        if (jo["FooBarBuzz"].Value<string>() == "B")
            return jo.ToObject<BFoo>(serializer);

        return null;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

using it:

var test = JsonConvert.DeserializeObject<List<BaseFoo>>(result, new JsonSerializerSettings() 
{ 
    Converters = { new FooConverter() }
});

taken from here


use the following JsonSerializerSettings construct while deserializing :

new JsonSerializerSettings()
{
    TypeNameHandling = TypeNameHandling.Objects
})

Tags:

C#

Json.Net