Search code examples
c#jsonserializationjson.net

Json.net serialize/deserialize derived types?


json.net (newtonsoft)
I am looking through the documentation but I can't find anything on this or the best way to do it.

public class Base
{
    public string Name;
}
public class Derived : Base
{
    public string Something;
}

JsonConvert.Deserialize<List<Base>>(text);

Now I have Derived objects in the serialized list. How do I deserialize the list and get back derived types?


Solution

  • If you are storing the type in your text (as you should be in this scenario), you can use the JsonSerializerSettings.

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

    Be careful, though. Using anything other than TypeNameHandling = TypeNameHandling.None could open yourself up to a security vulnerability - see "How to configure Json.NET to create a vulnerable web API".