How to deserialize a JSON property that can be two different data types using Json.NET

Viewed 34749

I'm using Json.NET for a project I'm working on. From an external API, I am receiving JSON with properties that are objects, but when they are empty 'false' is passed.

For example:

data: {
    supplier: {
        id: 15,
        name: 'TheOne'
    }
}

Could also be:

data: {
    supplier: false
}

How should I define the supplier property so that the supplier will be deserialized to a Supplier object or null.

Right now I have:

public class Data {
   [JsonProperty("supplier")]
   public SupplierData Supplier { get; set; }
}
public class SupplierData {
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
}

But now when trying to deserialize when supplier has a value of 'false' it fails. I would like the Supplier property to be null when the JSON value is 'false'.

I hope someone knows how to do this. Thanks.

1 Answers
Related