I have a class structure similar to this:
// Parent class
public class Circle
{
decimal Area { get; set; } = 0.2m;
}
// Child classes
public class GreenCircle : Circle
{
string Color { get; set; } = "Green";
}
public class RedCircle : Circle
{
string Color { get; set; } = "Red";
}
public class BlueCircle : Circle
{
string Color { get; set; } = "Blue";
}
// Class to convert
public class Shapes
{
public string ShapeType { get; set; } = "Circle";
List<Circle> ShapeList { get; set; } = new List<Circle>
{
new RedCircle(),
new BlueCircle(),
new GreenCircle(),
};
}
I want to serialize/deserialize the Shapes
class to json where the json string looks something like this:
{
"shapeType": "circle",
"shapeList": [
{"name": "RedCircle", "color": "red", "area": 0.2},
{"name": "BlueCircle", "color": "blue", "area": 0.2},
{"name": "GreenCircle", "color": "green", "area": 0.2}
]
}
I believe the way is to create a custom JsonConverter for it and I think I can manage the serialization part, but I have trouble deserializing the json:
- How can I deserialize a json which has normal filed and array filed in it?
- Is it possible to deserialize the list directly to the "child" objects? (i.e. to have a list with a
RedCircle
,BlueCircle
andGreenCircle
object instead of having a list with 3Circle
object)