问题
I am trying to deserialize the following json using Json.Net into C# classes as defined below. I am having this exception:
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.'
[
{
"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"
}
]
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);
回答1:
The exception is pretty clear. You cannot deserialize into an abstract class (or an interface).
That's because Json.Net is going to create a new instance of the type you requested (ShapeDto) and fill its properties. Since the type you requested is abstract, it cannot be constructed.
And if you try to make it non-abstract, it won't have the specific properties of the Circle and Line classes.
This means you cannot deserialize generically like you're trying to do. You have to know the type beforehand if you are going to deserialize to a type.
来源:https://stackoverflow.com/questions/57236221/exception-occurs-when-trying-to-deserialize-using-json-net