繁体   English   中英

无法创建类型 X 的实例。类型是接口或抽象类,无法实例化

[英]Could not create an instance of type X. Type is an interface or abstract class and cannot be instantiated

使用版本 7.0.1 Beta3,我正在尝试序列化/反序列化具有抽象类数组属性的复杂 POCO。 这些数组可以包含派生自抽象类的类的实例。

在序列化时,一切似乎都很好。 下面的 Json 片段显示类型信息设置正确。

Json 片段:

 "Items": 
 [
     {
         "$type": "IVXB_TS, ...",
         "inclusive": true,
         "value": "20091231"
     }
 ]

但是反序列化失败并出现以下错误:

无法创建 QTY 类型的实例。 类型是接口或抽象类,不能实例化。

类层次结构如下:

[System.Xml.Serialization.XmlIncludeAttribute(typeof(IVXB_TS))]
public abstract partial class ANY : object, System.ComponentModel.INotifyPropertyChanged
{
}

[System.Xml.Serialization.XmlIncludeAttribute(typeof(IVXB_TS))]
public abstract partial class QTY : ANY
{
}

[System.Xml.Serialization.XmlIncludeAttribute(typeof(IVXB_TS))]
public partial class TS : QTY
{
}

public partial class IVXB_TS : TS
{
}

项目属性:

[System.Xml.Serialization.XmlElementAttribute("high", typeof(IVXB_TS))]
[System.Xml.Serialization.XmlElementAttribute("low", typeof(IVXB_TS))]
public QTY[] Items

Json 片段中的类型信息似乎没有被使用。 这是反序列化配置问题吗?

解决这个问题的方法是配置反序列化器使用 json 中的类型信息 默认情况下不使用它。

序列化是这样完成的:

Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());
serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
serializer.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
serializer.Formatting = Newtonsoft.Json.Formatting.Indented;

using (StreamWriter sw = new StreamWriter(fileName))
using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
{
    serializer.Serialize(writer, obj, typeof(MyDocumentType));
}

在反序列化时,必须设置 TypeNameHandling 的设置:

MyDocumentType  obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MyDocumentType>(File.ReadAllText(fileName), new Newtonsoft.Json.JsonSerializerSettings 
{ 
    TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto,
    NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
});

就我而言,将TypeNameHandling设置为Auto并不能解决问题,但将其设置为All可以解决问题。 由于TypeNameHandling = TypeNameHandling.All对我来说似乎有点矫枉过正,所以我再次选择了Auto ,但这一次,我也将根对象的类型传递给了JsonConvert.SerializeObject函数:

var settings = new JsonSerializerSettings{ TypeNameHandling = TypeNameHandling.Auto };

var json = JsonConvert.SerializeObject(obj, typeof(ObjType), settings);

var deserializedObj = JsonConvert.DeserializeObject<ObjType>(json, settings);

如果您指定空值处理,您将不会收到此错误。

    new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    }));

您还可以设置[JsonIgnore]标志

JsonIgnore 标志的图像

对于将我带到这里的用例,这两个选项都可以正常工作。

类型名称处理不是必需的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM