What is the main purpose (or advantage) of having $type
value generated in JSON data? Does it simplify deserialization in some way?
I enabled this by setting TypeNameHandling
property of (de)serializer, because my intent was to have a strong validation, especially during deserialization. But now I see that deserializer have no problem deserializing data, even without generated $type
information.
So, please, what is the usecase for using $type
with Newtonsoft JSON?
the setting allows you to serialize classes which have interfaces or (abstract) base classes in their type definition.
consider these types:
public class MySerializableClass
{
public IOther Other {get;set;}
public BaseClass Base {get;set;}
}
public interface IOther
{
public string Foo {get;set;}
}
public abstract class BaseClass
{
public int MyNumber {get;set;}
}
if you do something like this:
JsonConvert.DeserializeObject<MySerializableClass>(json);
json.net does not know how to created instances of IOther and Baseclass, because they're abstract. so it offers you this setting to support serialization of such base classes or interfaces, because it stores the type of the instance of that property in the $type member of the resulting json.
bun in general would suggest you dont do this, because type names in json thats stored to a db or something are subject to change (namespaces change etc.) and are problematic to deserialize while the code changes.