This Imgur api call returns a list containing both Gallery Image and Gallery Album classes represented in json.
I cant see how to deserialize these automatically using Json.NET given that there is no $type property telling the deserializer which class is meant to be represented. There is a property called "IsAlbum" that can be used to differentiate between the two.
This question appears to show one method but it looks like a bit of a hack.
How do I go about deserializing these classes? (using C#, Json.NET).
Sample Data:
Gallery Image
{
"id": "OUHDm",
"title": "My most recent drawing. Spent over 100 hours.",
...
"is_album": false
}
Gallery Album
{
"id": "lDRB2",
"title": "Imgur Office",
...
"is_album": true,
"images_count": 3,
"images": [
{
"id": "24nLu",
...
"link": "http://i.imgur.com/24nLu.jpg"
},
{
"id": "Ziz25",
...
"link": "http://i.imgur.com/Ziz25.jpg"
},
{
"id": "9tzW6",
...
"link": "http://i.imgur.com/9tzW6.jpg"
}
]
}
}
You can do this fairly easily by creating a custom
JsonConverter
to handle the object instantiation. Assuming you have your classes defined something like this:You would create the converter like this:
Here's an example program showing the converter in action:
And here is the output of the above program:
Simply with JsonSubTypes attributes that work with Json.NET
Following implementation should let you de-serialize without changing the way you have designed your classes and by using a field other than $type to decide what to de-serialize it into.
I'm only posting this to clear up some of the confusion. If you are working with a predefined format and need to deserialize it, this is what I found worked best and demonstrates the mechanics so that others can tweak it as needed.