本文探討如何使用JSON.NET處理API返回的JSON數據中,屬性值既可能是單個字符串,也可能是字符串數組的情況。 以SendGrid事件API為例,其categories
屬性可能為單個字符串或字符串數組。
SendGrid事件API返回的JSON數據中,categories
屬性的格式不一致,可能是單個字符串,也可能是字符串數組,這給反序列化帶來了挑戰。
示例JSON:
<code class="language-json">[ { "email": "test1@example.com", "timestamp": 1337966815, "category": [ "newuser", "transactional" ], "event": "open" }, { "email": "test2@example.com", "timestamp": 1337966815, "category": "olduser", "event": "open" } ]</code>
為了優雅地解決這個問題,最佳方案是創建一個自定義的JsonConverter
。 該轉換器能夠識別categories
屬性的值類型,並將其正確反序列化為List<string>
。
代碼示例:
<code class="language-csharp">using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; public class Item { [JsonProperty("email")] public string Email { get; set; } [JsonProperty("timestamp")] public int Timestamp { get; set; } [JsonProperty("event")] public string Event { get; set; } [JsonProperty("category")] [JsonConverter(typeof(SingleOrArrayConverter<string>))] public List<string> Categories { get; set; } } public class SingleOrArrayConverter<T> : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(List<T>); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JToken token = JToken.Load(reader); if (token.Type == JTokenType.Array) { return token.ToObject<List<T>>(); } if (token.Type == JTokenType.Null) { return null; } return new List<T> { token.ToObject<T>() }; } public override bool CanWrite => false; // 只支持反序列化 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } public class Example { public static void Main(string[] args) { string json = @" [ { ""email"": ""test1@example.com"", ""timestamp"": 1337966815, ""category"": [ ""newuser"", ""transactional"" ], ""event"": ""open"" }, { ""email"": ""test2@example.com"", ""timestamp"": 1337966815, ""category"": ""olduser"", ""event"": ""open"" } ]"; List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json); foreach (var item in items) { Console.WriteLine($"Email: {item.Email}, Timestamp: {item.Timestamp}, Event: {item.Event}, Categories: {string.Join(", ", item.Categories)}"); } } }</code>
此代碼定義了一個Item
類和一個泛型SingleOrArrayConverter
。 SingleOrArrayConverter
能夠處理單個值和數組,並將其轉換為List<string>
。 主程序演示瞭如何使用該轉換器反序列化JSON數據。 注意,此轉換器只支持反序列化(CanWrite => false
)。
以上是如何處理同一屬性的單個項目或數組的JSON.NET?的詳細內容。更多資訊請關注PHP中文網其他相關文章!