Deserializing polymorphic json classes without type information using json.net
c#, imgur, json.net, serialization
Solution
Simple with my package that provides the `JsonSubTypes` attribute that works with Json.NET:
[JsonConverter(typeof(JsonSubtypes), "is_album")]
[JsonSubtypes.KnownSubType(typeof(GalleryAlbum), true)]
[JsonSubtypes.KnownSubType(typeof(GalleryImage), false)]
public abstract class GalleryItem
{
public string id { get; set; }
public string title { get; set; }
public string link { get; set; }
public bool is_album { get; set; }
}
public class GalleryImage : GalleryItem
{
// ...
}
public class GalleryAlbum : GalleryItem
{
public int images_count { get; set; }
public List<GalleryImage> images { get; set; }
}
Problem
This Imgur api call returns a list containing both Gallery Image and Gallery Album classes represented in JSON. I can't 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" } ] } } ```
Related problems
- What are @JsonTypeInfo and @JsonSubTypes used for in jackson
- Is polymorphic deserialization possible in System.Text.Json?
- Polymorphic JSON Deserialization failing using Json.Net
- Deserialize Json Object to polymorphic C# object without typeNameHandling
- Custom inheritance JsonConverter fails when JsonConverterAttribute is used