I'm using .NET's JavascriptSerializer
to deserialize JSON into runtime objects and for the most part the mapping between JSON fields and object fields has been automatic. However, I am faced with the following scenario and would welcome advice on how to handle it.
Imagine we have a JSON representation of a Shape, which can be a Square or a Circle. For example,
{"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; // either "Square" or "Circle"
public Shape Shape;
}
class Shape // all Shapes have a Color
{
public string Color;
}
class Square : Shape
{
public float Side;
}
class Circle : Shape
{
public float Radius;
}
Simply calling JavascriptSerializer.Deserialize
doesn't work in this case, where there is a variant type involved. Is there any way to coax JavascriptSerializer
to deserialize despite the "branch" in my data type? I am also open to third-party solutions.