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);
}
}
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});
}
}