How to work with JSON and object variants?

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

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.

+5
2

, , . , , .

:

JSON JsonConvert.DeserializeObject

"ShapeType", Shape (Square Circle) .

( , , ;)

+2

, JavascriptSerializer JavaScriptTypeResolver, (SimpleTypeResolver ):

new JavaScriptSerializer(new SimpleTypeResolver());

. , __type JSON, .

+1

All Articles