Json.NET無類型信息的多態JSON反序列化
Json.NET強大的功能允許即使在沒有類型信息的情況下也能反序列化多態JSON數據。這在處理返回不同對像類型混合的數據源時尤其有用,例如,Imgur API同時返回Gallery Image和Gallery Album類的情況。
為了實現這一點,我們創建了一個自定義JsonConverter來處理對象實例化過程。首先,我們定義我們的GalleryItem基類及其派生類GalleryImage和GalleryAlbum:
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; } }
接下來,我們實現我們的JsonConverter,GalleryItemConverter:
public class GalleryItemConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(GalleryItem).IsAssignableFrom(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // 解析包含数据的JSON对象 JObject jo = JObject.Load(reader); // 检查是否存在"is_album"以确定对象类型 bool? isAlbum = (bool?)jo["is_album"]; GalleryItem item; if (isAlbum.GetValueOrDefault()) item = new GalleryAlbum(); else item = new GalleryImage(); // 使用JsonSerializer填充对象的属性 serializer.Populate(jo.CreateReader(), item); return item; } // 对于我们的目的,不需要实现CanWrite和WriteJson }
轉換器檢查是否存在“is_album”屬性以確定要實例化的類型。然後,它使用JsonSerializer根據JSON對像中的數據填充對象的屬性。
為了演示其用法,我們定義了一個解析提供的示例數據的示例程序:
string json = @" [ { ""id"": ""OUHDm"", ""title"": ""My most recent drawing. Spent over 100 hours."", ""link"": ""http://i.imgur.com/OUHDm.jpg"", ""is_album"": false }, { ""id"": ""lDRB2"", ""title"": ""Imgur Office"", ""link"": ""http://alanbox.imgur.com/a/lDRB2"", ""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"" } ] } ]"; List<GalleryItem> items = JsonConvert.DeserializeObject<List<GalleryItem>>(json, new GalleryItemConverter());
程序的輸出展示了Gallery Image和Gallery Album對象的成功反序列化,以及它們各自屬性的準確填充。
通過這種方式,自定義JsonConverter允許我們處理多態JSON反序列化,而無需顯式類型信息,使我們能夠與不同的數據源無縫協作。
以上是如何在沒有類型信息的情況下在JSON.NET中執行多態性JSON避難所?的詳細內容。更多資訊請關注PHP中文網其他相關文章!