尝试使用Json.Net反序列化时发生异常 [英] Exception occurs when trying to deserialize using Json.Net

查看:233
本文介绍了尝试使用Json.Net反序列化时发生异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Json.Net将以下json反序列化为C#类,如下所示.我有这个例外:

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:'无法创建 Viewer.ShapeDto类型的实例.类型是接口还是抽象 类,不能实例化.路径"[0] .type",第3行,位置 13.'

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);

推荐答案

该异常非常明显.您不能反序列化为抽象类(或接口).

The exception is pretty clear. You cannot deserialize into an abstract class (or an interface).

这是因为Json.Net将创建您请求的类型(ShapeDto)的新实例并填充其属性.由于您请求的类型是抽象类型,因此无法对其进行构造.

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.

如果您尝试使其不抽象,则它将没有Circle和Line类的特定属性.

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.

这篇关于尝试使用Json.Net反序列化时发生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆