An API server endpoint can return one of the followings:
{
"type": "apple",
"color": "red"
}
which can be deserialized into the class Apple
or
{
"type": "orange",
"size": "big"
}
which can be deserialized into the class Orange
.
I've created a class Fruit
with just one property fruitInstance
(which is an object
) and it will store an instance of either Apple
or Orange
.
Is there a way I can customize the JSON.NET deserializer of Fruit
to do the following?
- Go through possible fruit types one by one (only
Apple
,Orange
in this case but we can support more later) - Try to deserialize the response (JSON string) into
Apple
for example - If the deserialization throws exception, try next one (e.g.
Orange
) until the deserialization is successful - On success, store the deserialized instance (e.g. Orange) in the
frusitInstance
property
UPDATE: Fruit is not a parent class of Apple/Orange and we cannot make it so due to requirement. In other words, we cannot use JsonSubTypes
. Let's imagine later the payload can be an integer (e.g. 15) and Fruit will be able to deserialize the payload (integer) into an Integer and store it in fruitInstance
.