This project has moved and is read-only. For the latest updates, please go here.

Using a custom type discriminator to tell which type of a class hierarchy to deserialize

Jul 6, 2012 at 12:57 AM
Edited Jul 6, 2012 at 12:58 AM


This was originally posted at Stack Overflow, however I haven't found anything indicating whether it can be done or not.

Assuming I have a class hierarchy, I'm curious whether I can use a custom type discriminator  (called "type", "discriminator" or anything making sense in my case) to tell which type to create when a JSON payload is deserialized.

For example, assuming I have a stream with the following contents, I'd like it to deserialize an NonProfitOrganization.

   "type": "non-profit"
   /* other properties related to non profit */

and if I have a stream with the following contents, I'd like it to deserialize an Company.

   "type": "company"
   /* other properties related to companies */

By using the "type" property to create the correct class in following hierarchy:

public abstract class Organization
    /* properties related to all organizations */

public sealed class Company : Organization
     /* properties related to companies */

public sealed class NonProfitOrganization : Organization
     /* properties related to non profit organizations */

when I try to deserialize the payload to an organization as follows:

Newtonsoft.Json.JsonSerializer serializer = Newtonsoft.Json.JsonSerializer.Create(serializerSettings);
var reader = new JsonTextReader(new StreamReader(stream));
Organization result = (Organization)serializer.Deserialize(reader, typeof(Organization));
return result;

Is this possible? If so, could you provide me with any example of how it can be done?

Thanks in advance,