Home > Backend Development > C++ > How can I handle JSON.net deserialization of a single item or array for the same property?

How can I handle JSON.net deserialization of a single item or array for the same property?

Barbara Streisand
Release: 2025-02-02 20:46:12
Original
434 people have browsed it

Single project or array of the same attribute in json.net

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.

Question: In the JSON data returned by the

Sendgrid event API, the format of the

attribute is inconsistent. It may be a single string or a string array, which brings a challenge to the device. categories

Example 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>
Copy after login
solution: custom JSONCONVERR

In order to solve this problem elegantly, the best solution is to create a custom

. The converter can identify the value type of the JsonConverter attribute and transform it correctly to categories. List<string>

Code example:

<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>
Copy after login
This code defines a

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template