I find the following dilemma often. Suppose you're retrieving Json messages from a database, message bus, event store or whatever, and you need to deserialize each message into the proper type. Something like var deserializedObject = Json.Deserialize<?>(jsonMessage);

What's the best strategy/design to do so?

I guess the Json must contain some kind of type metadata that helps the deserializer to know which object to deserializer it into. Is that right? Is there any good article on this?

If that's the right approach then the Json would have something like '$type': 'MyClass'

Would there be an alternative? Maybe some functionality that grabs the Json and deserializes it into a dynamic object and later it starts iterating over the "known" types trying to find a match between the Json structure and a known type?

Again, any good article about this or example, better if with c#, would be much appreciated.

Update: Some interesting things I have found in case someone knows a bit about it. MongoDb is capable of storing objects with abstract or interface properties and later on it knows how to deserialize them because it stores a type discriminator _t with the Bson document. That's why I thought that maybe some metadata is always required along with a list of known types.

  • 1
    yes, adding a type field is the normal way
    – Ewan
    Sep 20, 2018 at 18:13


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.