Home » c# » Json.net serialize/deserialize derived types?

Json.net serialize/deserialize derived types?

Posted by: admin November 29, 2017 Leave a comment

Questions:

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?

Answers:

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

Questions:
Answers:

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

Base object1 = new Base() { name = "Object1" };
Derived object2 = new Derived() { something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct desirialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.