![](/img/trans.png)
[英]Could not create an instance of type . Type is an interface or abstract class and cannot be instantiated
[英]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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.