Home > Backend Development > C++ > How to Handle JSON Data with Mixed Single and Array Values for the Same Property?

How to Handle JSON Data with Mixed Single and Array Values for the Same Property?

Linda Hamilton
Release: 2025-02-02 21:06:09
Original
263 people have browsed it

How to Handle JSON Data with Mixed Single and Array Values for the Same Property?

JSON data

Question:

When processing JSON data, the same attribute can often be expressed as a single value, or it can be represented as a value array. For example, the following valid loads obtained from Sendgrid API:

"Category" attribute illustrates this problem. For certain projects, it is a string, and for other items, it is a string array. JSON.NET provides two methods to deal with this inconsistency: modify the transmitted data or configure json.net to accept differences.

<code class="language-json">[
  {
    "email": "[email protected]",
    "timestamp": 1337966815,
    "category": [
      "newuser",
      "transactional"
    ],
    "event": "open"
  },
  {
    "email": "[email protected]",
    "timestamp": 1337966815,
    "category": "olduser",
    "event": "open"
  }
]</code>
Copy after login
Solution: Jsonconveter

The recommended method is to use custom JSONCONVERRER. Let us define a class to retrofit data:

For the attributes that may be a single item or array (in this example, "Category"), we define it as list

and specify a custom converter to process its retrofit.

<code class="language-csharp">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; }
}</code>
Copy after login
The following is the implementation of the converter:

This converter determines whether the label passed into an array or a single item is processed accordingly. If it is an array, it converts it to List

; otherwise, it will pack the project in a new list.

<code class="language-csharp">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
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}</code>
Copy after login
Usage and output

To use a custom converter, please update the derivative code as shown below:

The program will be correctly serialized JSON data, and the "Category" attribute will be appropriately filled into a string list for a single situation and array situation.

This method provides a flexible method to process JSON data with the same property with a mixed value type. It does not need to modify the data or cause potential data loss due to inconsistent processing.

The above is the detailed content of How to Handle JSON Data with Mixed Single and Array Values 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