I am trying to convert the following JSON into C# classes using Json.Net. However, I am getting an exception. Here is the JSON:
Newtonsoft.Json.JsonSerializationException: 'Could not create an instance of type Viewer.ShapeDto. Type is an interface or abstract class and cannot be instantiated. Path '[0].type', line 3, position 13.'
Here is the JSON:
[
{
"type":"line",
"a":"-1,5; 3,4",
"b":"2,2; 5,7",
"color":"127; 255; 255; 255",
"lineType":"solid"
},
{
"type":"circle",
"center":"0; 0",
"radius":15.0,
"filled":false,
"color":"127; 255; 0; 0",
"lineType":"dot"
}
]
And here are the C# classes I am using:
public abstract class ShapeDto
{
[JsonProperty(PropertyName = "type")]
public abstract string Type { get; }
[JsonProperty(PropertyName = "color")]
public string Color { get; set; }
[JsonProperty(PropertyName = "lineType")]
public string LineType { get; set; }
}
public sealed class LineDto : ShapeDto
{
public override string Type => "line";
[JsonProperty(PropertyName = "a")]
public string A { get; set; }
[JsonProperty(PropertyName = "b")]
public string B { get; set; }
}
public sealed class CircleDto : ShapeDto
{
public override string Type => "circle";
[JsonProperty(PropertyName = "center")]
public string C { get; set; }
[JsonProperty(PropertyName = "radius")]
public double R { get; set; }
[JsonProperty(PropertyName = "filled")]
public bool Filled { get; set; }
}
var settings = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.All};
var shapes = JsonConvert.DeserializeObject<IList<ShapeDto>>(json, settings);