Search code examples
c#json.net

how to deserialize JSON into IEnumerable<BaseType> with Newtonsoft 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.


Solution

  • 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