尝试使用Json.Net反序列化时发生异常

编程入门 行业动态 更新时间:2024-10-24 04:34:03
本文介绍了尝试使用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反序列化时发生异常

本文发布于:2023-11-16 22:11:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607674.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   发生   序列化   Json   Net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!