赞
踩
在开发中定义了一个抽象类,序列号抽象类的子类时,出现如下问题:
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
属性 | 值 | 描述 |
---|---|---|
None | 0 | 序列化类型时不要包含.NET类型名称。 |
Objects | 1 | 序列化为JSON对象结构时包括.NET类型名称。 |
Arrays | 2 | 序列化为JSON数组结构时包含.NET类型名称。 |
All | 3 | 始终在序列化时包含.NET类型名称。 |
Auto | 4 | 当序列化对象的类型与其声明的类型不同时,请包含.NET类型名称。请注意,默认情况下,这不包括根序列化对象。要在JSON中包含根对象的类型名称,必须使用SerializeObject(Object,Type,JsonSerializerSettings) 或Serialize(JsonWriter,Object,Type)指定根类型对象。 |
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。