2

I am currently trying to build a message engine. This message receives a JSON string that can represent multiple classes as for example:

Class1 has properties A and B Class2 has properties X and Y

How do I know what class to deserialize into? Is there a way to detect that the string represents a Class1 object or a Class2?

Thank you

Luis Simoes
  • 53
  • 1
  • 8
  • 1
    There are already several examples of `JsonConverter` implementations that load the JSON into an intermediate `JsonDocument` and query for the presence of certain properties. See e.g. [Deserialize complex polymorphic types with System.Text.Json]https://stackoverflow.com/q/62949042/3744182), [Is polymorphic deserialization possible in System.Text.Json?](https://stackoverflow.com/a/59785679/3744182) and [Serialize/Deserialize a class hierarchy with .NET Core System.Text.Json](https://stackoverflow.com/q/58225122/3744182). Do those answer your questions? – dbc Jul 23 '20 at 15:49
  • I think these articles explain how to "tag" your classes but when you control the serialization and deserialization. In my case the JSON text is being sent by an external application and with different formats that I need to somehow detect in order to convert to the right object. Is wondering how to achieve this... – Luis Simoes Jul 26 '20 at 08:37
  • 1
    This one seems to be what you want: [System.Text.Json and Dynamically Parsing polymorphic objects](https://stackoverflow.com/questions/60792311/system-text-json-and-dynamically-parsing-polymorphic-objects). The accepted answer implements a `JsonConverter` which pre-loads the JSON into a `JsonDocument`, tests for the presence of certain properties, and deserializes to the final type based on the property or properties found. It has a bug though, `JsonDocument` needs to be disposed after use. – dbc Jul 26 '20 at 14:41
  • 1
    Thanks! It worked after a few tweaks. Much appreciated for the assistance. – Luis Simoes Jul 26 '20 at 20:17

0 Answers0