1

I'm writing a parser for configuration jsons from a particular game. The structure is sometimes complicated (say there can be a "Tape" class object, which holds different objects for different animation types, i.e. SizeAnim, TranslationAnim etc.). The class name for every object is always supplied though a "__class" value in the json. So it looks something like this:

{
  "__class": "Tape",
  "Animations": [{
      "__class": "SizeAnim",
      "AnimationData": "somedata"
   },
   {
      "__class": "TranslationAnim",
      "DifferentData": ""
   }]
}

Now the question is: is it possible to instruct the json serializer/deserializer to use the "__class" field, instead of "$type" to determine the type of the object?

Vlad Sineok
  • 99
  • 1
  • 1
  • 9
  • Tape is a C# class in your code? – Emanuele Jun 11 '21 at 10:56
  • @Emanuele yes, SizeAnim and TranslationAnim are too. – Vlad Sineok Jun 11 '21 at 11:00
  • And in Tape class do you have a SizeAnim property/variable? – Emanuele Jun 11 '21 at 11:05
  • @Emanuele no, there's an Animations property, which is a list of objects. – Vlad Sineok Jun 11 '21 at 11:08
  • Looks like not, see [JSON.Net - Change $type field to another name?](https://stackoverflow.com/q/9490345/3744182). That question does have answers showing how to subclass `JsonTextReader` to rename some other type discriminator to `$type` on the fly. – dbc Jun 11 '21 at 13:56
  • Alternatively, for polymorphic values, you could write a custom `JsonConverter` that preloads to a `JToken` and checks the `__class` property along the lines of the ones from [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182), [Json.Net Serialization of Type with Polymorphic Child Object](https://stackoverflow.com/q/29528648/3744182) or [How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?](https://stackoverflow.com/q/8030538/3744182). – dbc Jun 11 '21 at 13:57
  • You will also need a [custom `ISerializationBinder`](https://www.newtonsoft.com/json/help/html/SerializeSerializationBinder.htm). See [Custom $type value for serialized objects](https://stackoverflow.com/q/49283251/3744182) and [Using a custom type discriminator to tell JSON.net which type of a class hierarchy to deserialize](https://stackoverflow.com/q/11099466/3744182) to do that. – dbc Jun 11 '21 at 14:07
  • Do those questions answer your question fully? – dbc Jun 11 '21 at 14:08

0 Answers0