0

If I know my string is one of many "known" object types can I deserialized it, without deserializing it multiple times, trying each known type and catching the error and then trying another until I find the matching type?

Is creating a schema based on each object type and then trying to validate the schema any better of an idea? It almost seems worse.

Noel
  • 1,968
  • 3
  • 20
  • 38
  • 4
    You can create a custom [`JsonConverter`](https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm) to deserialize a polymorphic object, by loading to a `JObject` and checking some type discriminator or the presence of appropriate properties. – dbc May 22 '21 at 23:23
  • 4
    Please see [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) for details. If those questions don't answer yours, please [edit] your question to add some additional details. – dbc May 22 '21 at 23:23
  • Or, if you can change your JSON format, you could use [`TypeNameHandling`](https://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm) as described in [Json.net serialize/deserialize derived types?](https://stackoverflow.com/q/8513042/3744182) or [how to deserialize JSON into IEnumerable with Newtonsoft JSON.NET](https://stackoverflow.com/q/6348215/3744182) - but watch out for the security risks explained in [TypeNameHandling caution in Newtonsoft Json](https://stackoverflow.com/q/39565954/3744182). – dbc May 23 '21 at 17:36
  • So far working through these suggestions, has not provided an answer. I am not looking to create a custom Deserializer for every object that I have. I am looking to deserialize to the correct object without additional work being done for each (new)object that is added. Using the datacontract serializer I can hand in a list of "known" types and it will deserialize corectly. Those known types need to be identified by an attribute. Is there something similar? I want to avoid the extra work. It would also be preferable to avoid the use of an attribute – Noel May 27 '21 at 18:59
  • Did you look into `TypeNameHandling` as described in [Json.net serialize/deserialize derived types?](https://stackoverflow.com/a/8763745/3744182)? If that doesn't meet your needs, can you please [edit] your question to clarify your requirements? Possibly `TypeNameSerializationBinder` from [Using a custom type discriminator to tell JSON.net which type of a class hierarchy to deserialize](https://stackoverflow.com/a/12203624/3744182) meets your needs? – dbc May 27 '21 at 19:15

0 Answers0