i have a problem and want to know if it is or if it will be possible with json.net
i have a superclass called A and two classes which inherit from it, B1 and B2 when
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
{
private IContractResolver resolver;
public MembaseJsonSerializer(IContractResolver resolver)
{
this.resolver = resolver;
}
public R FromJson(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.