2

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?

Andy Coarse
  • 25
  • 1
  • 6

1 Answers1

2

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.

stylefish
  • 561
  • 3
  • 17
  • So, if I am right, it instructs the deserializer which descendant class should be used for instantiating the data, OK? You suggest me not to use $type in this scenario or not to have interfaces and/or abstract classes at all in my JSON data structures? – Andy Coarse Nov 07 '17 at 22:09
  • i would suggest to have a "DTO" (data transfer object) / POCO (plain old clr object) class to use for serialization thats stored on disk or in a database, because over time if your code evolves and structures change, you descendant class might not exist anymore in the namespace thats stored in the $type member of the json structure. since i dont know your exact usecase i only wanted to point this out as i have made my (bad) experiences with this kind of data in a database ;) if you only use it temporary (to send it over the wire while your app runs) it might be ok to use this feature. – stylefish Nov 07 '17 at 22:16
  • Thank you for the answer. I have several DTO classes specially for transfering data over the network. I have some interface in the DTO design and using $type everywhere. But now I see it complicates things, so I was wondering about the real point of that. Validation is important for me also at server (javascript) side. I also maintain JSON schemas for DTOs, so I was looking for the easiest way of managing the schemas, DTOs and whole validation process at both sides. – Andy Coarse Nov 07 '17 at 22:30