Deserializing polymorphic json classes without type information using json.net

后端 未结 5 1156
暖寄归人
暖寄归人 2020-11-21 06:10

This Imgur api call returns a list containing both Gallery Image and Gallery Album classes represented in JSON.

I can\'t see how to

5条回答
  •  耶瑟儿~
    2020-11-21 06:39

    Simply with JsonSubTypes attributes that work 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 images { get; set; }
        }
    

提交回复
热议问题