I use .NET JavascriptSerializerto deserialize JSON in runtime objects, and for the most part, the mapping between JSON fields and object fields was automatic. However, I came across the following scenario and I will welcome advice on how to deal with it.
Imagine we have a JSON representation of a shape, which can be a square or a circle. For instance,
{"ShapeType":"Circle","Shape":{"Color":"Blue", "Radius":"5.3"}}
or
{"ShapeType":"Square","Shape":{"Color":"Red", "Side":"2.1"}}
These JSON strings are modeled after the class hierarchy shown below.
class ShapePacket
{
public string ShapeType;
public Shape Shape;
}
class Shape
{
public string Color;
}
class Square : Shape
{
public float Side;
}
class Circle : Shape
{
public float Radius;
}
Just the call JavascriptSerializer.Deserializedoes not work in this case when there is a variant type. Is there a way to persuade JavascriptSerializerdeserialize despite the “branch” in my data type? I am also open to third-party solutions.