我有一个问题,想知道它是否可以与json.net一起使用
我有一个叫做A的超类和两个继承它的类,B1和B2
当我创建一个类型A的列表,然后添加一些B1和B2,序列化和反序列化后,它们都是A类型.
是否有可能将每个继承的类转换为其以前的类类型,如B1或B2?
是的,只要您通知
JSON.Net您想要使用TypeNameHandling.All并使用适当的强制转换,它就应该有效.以下在我的项目中有效:
public class MembaseJsonSerializer<T> { private IContractResolver resolver; public MembaseJsonSerializer(IContractResolver resolver) { this.resolver = resolver; } public R FromJson<R>(object json) { if (typeof(T).IsAssignableFrom(typeof(R))) { object res = JsonConvert.DeserializeObject(json.ToString(),new JsonSerializerSettings() { ContractResolver = resolver,TypeNameHandling = TypeNameHandling.All }); return (R)res; } throw new NotImplementedException("Type is not assignable."); } public string ToJson(object obj) { if (typeof(T).IsAssignableFrom(obj.GetType())) { string json = JsonConvert.SerializeObject(obj,Formatting.None,new JsonSerializerSettings() { ContractResolver = resolver,TypeNameHandling = TypeNameHandling.All }); return json; } throw new NotImplementedException("Type is not assignable."); } }
其中T是基类,R是子类.