Exception occurs when trying to deserialize using Json.Net [duplicate]

拟墨画扇 提交于 2019-12-13 09:38:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!