Friedrich Ewald My Personal Website

Serialization and Deserialization with C# & JSON

For serialization and deserialization in the .NET framework, I use the Newtonsoft JSON Serializer. This library works really fast and is very flexible. Lately I had a problem that I wanted to serialize a List<ObjA> with ObjB and ObjC. ObjB and ObjC are children of ObjA. In the code it looks as the following:

public class ObjA
{}

public class ObjB : ObjA
{}

public class ObjC : ObjA
{}

public class Program
{
	public void main()
	{
		List<ObjA> objectList = new List<ObjA>();

		string serializedObjects = JsonConvert.SerializeObject(objectList);

		List<ObjA> objectListNew = JsonConvert.DeserializeObject<List<ObjA>>(serializedObjects);
	}
}
If I now serialized this with the method SerializeObject() and later deserialized it with the method DeserializeObject<>(), all the objects were of the type ObjA instead of type ObjB or ObjC. After a short research, I found the solution:
public class Program
{
	public void main()
	{
		List<ObjA> objectList = new List<ObjA>();

		string serializedObjects = JsonConvert.SerializeObject(objectList, Formatting.Indented, new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                TypeNameHandling = TypeNameHandling.All
            });

		List<ObjA> objectListNew = JsonConvert.DeserializeObject<List<ObjA>>(serializedObjects, new JsonSerializerSettings() {TypeNameHandling = TypeNameHandling.Auto});
	}
}
This preserves the types of the objects during serialization.


About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.