how to deserialize JSON into IEnumerable 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

Leave a Comment