0

Background

I am re-architecting a large project where data has been serialized to Json and stored in a database. Various property members of objects to be serialised may be of types derived from the member definition. So the property will be defined as an IFoo or BarBase, however represent a SpecialisedFoo or SpecialisedBar instance. In order to manage the serialisation the current implementation serialises the type to the Json and assemble to the json so that the deserialiser can know where to get the type from.
To my mind this is a bit of a smelly way of serialising/deserialisation because it ties the serialized data to the implmentation of the deserialised data.

Question

Is there a way of getting into the serialisation pipeline of the Newtonsoft Deserialiser with the data to be deserialised before the instantiation of the object so I have the choice over what type the deserialised object will be.

symaps
  • 62
  • 6
  • There are many options if you don't want to show the actual type in the `"$type"` property. You can use a custom `JsonConverter` to select the type, see e.g. [How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?](https://stackoverflow.com/q/8030538/3744182), [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182) or [Json.Net Serialization of Type with Polymorphic Child Object](https://stackoverflow.com/q/29528648/3744182). – dbc Jan 28 '20 at 19:01
  • A custom `ISerializationBinder` might also meet your needs, see [Custom $type value for serialized objects](https://stackoverflow.com/q/49283251/3744182) or [Using a custom type discriminator to tell JSON.net which type of a class hierarchy to deserialize](https://stackoverflow.com/q/11099466/3744182). – dbc Jan 28 '20 at 19:03
  • Since there are already many questions and answers around this topic, can you give more details to distinguish your problem? – dbc Jan 28 '20 at 19:04
  • Thanks dbc that was exactly what I was looking for. I would like to award this the accepted answer however you posted it as a comment so I am not sure how to give you the credit. – symaps Jan 29 '20 at 10:33
  • Which solution did you choose? The `JsonConverter` approach, or the `ISerializationBinder` approach? – dbc Jan 29 '20 at 10:36
  • I needed to use a combination of the two. – symaps Feb 04 '20 at 15:11

0 Answers0