This article discusses how to use JSON.NET to process the JSON data returned by the API. The attribute value may be both a single string or a string array. Taking the Sendgrid event API as an example, its categories
attribute may be a single string or a string array.
attribute is inconsistent. It may be a single string or a string array, which brings a challenge to the device. categories
<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>
. The converter can identify the value type of the JsonConverter
attribute and transform it correctly to 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>
class and a generic Item
. SingleOrArrayConverter
can handle single and array, and convert it to SingleOrArrayConverter
. The main program demonstrates how to use the converter's back serialization JSON data. Note that this converter only supports degradation (List<string>
). CanWrite => false
The above is the detailed content of How can I handle JSON.net deserialization of a single item or array for the same property?. For more information, please follow other related articles on the PHP Chinese website!