既然你已经添加
[JsonConverter(typeof(JsonProductConverted))]直接到你的
Product类型,你可以一个虚拟的转换器添加到
ProductImpl该收益
false来自
CanRead与
CanWrite:
[JsonConverter(typeof(NoConverter))]public class ProductImpl : Product{}public class NoConverter : JsonConverter{ public override bool CanConvert(Type objectType) { return false; } public override bool CanRead { get { return false; } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanWrite { get { return false; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); }}
这将覆盖基类的转换器,然后回退到用于读取和写入的默认序列化
样本.Net小提琴。
另一种选择是使用
serializer.Populate()。这样可以避免调用对象本身的转换器:
public class JsonProductConverted : JsonTypeInferringConverterbase{ protected override Type InferType(Type objectType, JObject json) { //var type = GetTypeFromId((int) json["typeId"]); // Construct type from field in return typeof(ProductImpl); } public override bool CanConvert(Type objectType) { return false; }}public abstract class JsonTypeInferringConverterbase : JsonConverter{ public override bool CanWrite { get { return false; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } protected abstract Type InferType(Type objectType, JObject json); protected virtual object CreateObject(Type actualType, JsonSerializer serializer, JObject json) { var contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(actualType); return contract.DefaultCreator(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; var json = JObject.Load(reader); var actualType = InferType(objectType, json); // Construct object (or reuse existingValue if compatible) if (existingValue == null || !actualType.IsAssignableFrom(existingValue.GetType())) { existingValue = CreateObject(actualType, serializer, json); } // Populate object. using (var subReader = json.CreateReader()) { serializer.Populate(subReader, existingValue); } return existingValue; }}
请注意,具体对象必须具有无参数的构造函数才能起作用。如果没有,您可以
protected virtual object CreateObject(TypeactualType, JsonSerializer serializer, JObjectjson)通过反序列化内的select属性来覆盖并手动调用参数化的构造函数
JObject json。
样本小提琴2。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)