Cet article examine comment utiliser JSON.net pour traiter les données JSON renvoyées par l'API. Prenant l'exemple de l'API Event SendGrid, son attribut categories
peut être une chaîne unique ou un tableau de chaîne.
est incohérent. categories
[ { "email": "test1@example.com", "timestamp": 1337966815, "category": [ "newuser", "transactional" ], "event": "open" }, { "email": "test2@example.com", "timestamp": 1337966815, "category": "olduser", "event": "open" } ]
. Le convertisseur peut identifier le type de valeur de l'attribut JsonConverter
et le transformer correctement en categories
. List<string>
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)}"); } } }
et un générique Item
. SingleOrArrayConverter
peut gérer un seul et un tableau, et le convertir en SingleOrArrayConverter
. Le programme principal montre comment utiliser les données JSON de sérialisation arrière du convertisseur. Notez que ce convertisseur ne prend en charge que la dégradation (List<string>
). CanWrite => false
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!