Yes, it should work as long as you inform JSON.Net that you want to use TypeNameHandling.All and use appropriate casting. The following works in my project:
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.");
}
}
Where T is the base class and R is the sub class.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…