Could not create an instance of type T. Type is an interface or abstract class

在开发中定义了一个抽象类,序列号抽象类的子类时,出现如下问题:

Could not create an instance of type TestJsonConvert.IDevice. Type is an interface or abstract class and cannot be instantiated.

解决方法:

在JsonSerializerSettings中设置TypeNameHandling 属性为TypeNameHandling.Auto即可。如下所示:

public abstract class Business
{
    public string Name { get; set; }
}

public class Hotel : Business
{
    public int Stars { get; set; }
}

public class Stockholder
{
    public string FullName { get; set; }
    public IList<Business> Businesses { get; set; }
}


Stockholder stockholder = new Stockholder
{
    FullName = "Steve Stockholder",
    Businesses = new List<Business>
    {
        new Hotel
        {
            Name = "Hudson Hotel",
            Stars = 4
        }
    }
};

string jsonTypeNameAll = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
});

Console.WriteLine(jsonTypeNameAll);
// {
//   "$type": "Newtonsoft.Json.Samples.Stockholder, Newtonsoft.Json.Tests",
//   "FullName": "Steve Stockholder",
//   "Businesses": {
//     "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Samples.Business, Newtonsoft.Json.Tests]], mscorlib",
//     "$values": [
//       {
//         "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",
//         "Stars": 4,
//         "Name": "Hudson Hotel"
//       }
//     ]
//   }
// }

string jsonTypeNameAuto = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Auto
});

Console.WriteLine(jsonTypeNameAuto);
// {
//   "FullName": "Steve Stockholder",
//   "Businesses": [
//     {
//       "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",
//       "Stars": 4,
//       "Name": "Hudson Hotel"
//     }
//   ]
// }

// for security TypeNameHandling is required when deserializing
Stockholder newStockholder = JsonConvert.DeserializeObject<Stockholder>(jsonTypeNameAuto, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Auto
});

Console.WriteLine(newStockholder.Businesses[0].GetType().Name);
// Hotel

总结

属性描述
None0序列化类型时不要包含.NET类型名称。
Objects1序列化为JSON对象结构时包括.NET类型名称。
Arrays2序列化为JSON数组结构时包含.NET类型名称。
All3始终在序列化时包含.NET类型名称。
Auto4当序列化对象的类型与其声明的类型不同时,请包含.NET类型名称。请注意,默认情况下,这不包括根序列化对象。要在JSON中包含根对象的类型名称,必须使用SerializeObject(Object,Type,JsonSerializerSettings) 或Serialize(JsonWriter,Object,Type)指定根类型对象。
System.Reflection.TargetInvocationException HResult=0x80131604 Message=Exception has been thrown by the target of an invocation. Source=System.Private.CoreLib StackTrace: 在 System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr) 在 System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) 在 Tensorflow.Keras.Utils.generic_utils.deserialize_keras_object(String class_name, JToken config) 在 Tensorflow.Keras.Saving.KerasObjectLoader._revive_layer_or_model_from_config(KerasMetaData metadata, Int32 node_id) 在 Tensorflow.Keras.Saving.KerasObjectLoader._revive_from_config(String identifier, KerasMetaData metadata, Int32 node_id) 在 Tensorflow.Keras.Saving.KerasObjectLoader._load_layer(Int32 node_id, String identifier, String metadata_json) 在 Tensorflow.Keras.Saving.KerasObjectLoader.load_layers(Boolean compile) 在 Tensorflow.Keras.Saving.SavedModel.KerasLoadModelUtils.load(String path, Boolean compile, LoadOptions options) 在 Tensorflow.Keras.Saving.SavedModel.KerasLoadModelUtils.load_model(String filepath, IDictionary`2 custom_objects, Boolean compile, LoadOptions options) 在 Tensorflow.Keras.Models.ModelsApi.load_model(String filepath, Boolean compile, LoadOptions options) 在 Keras.NET_Prediction_main_program.Program.Main() 在 D:\编程软件系列\VS2022社区版\文件\Keras.NET Prediction main program\Program.cs 中: 第 30 行 此异常最初是在此调用堆栈中引发的: [外部代码] 内部异常 1: JsonSerializationException: Could not create an instance of type Tensorflow.Keras.IRegularizer. Type is an interface or abstract class and cannot be instantiated. Path 'kernel_regularizer'.
08-28
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值