1

I'm parsing some JSON data I receive from a server using the built-in System.Text.Json module.

Here's an example class that I would use:

public class Something
{
        [JsonPropertyName("items")]
        public Item[] Items { get; set; }
}

The JSON data for this is usually received like the following, and it's properly parsed with JsonSerializer.Deserialize<Something>():

{
        "items": [ { ... }, { ... }, { ... } ]
}

However, when there's no items, the server instead returns an empty object, which causes an exception because it expected an array.

{
        "items": {}
}

Is there any way I could set it so that an empty object would be considered as an empty array? I've seen that you can make a custom JSON converter but I struggled to get it working.

Serge
  • 40,935
  • 4
  • 18
  • 45
  • This is the exact same problem as [this question](https://stackoverflow.com/questions/72770505/deserialization-json-object-vs-array#comment128536222_72770505) except the exact opposite. the solution is the same (as is my comment!) – Jamiec Jun 28 '22 at 16:10
  • I've never worked with `System.Text.Json`, but here's a way to solve your issue with a custom [`Newtonsoft.Json` converter](https://stackoverflow.com/questions/31186715/deserialize-json-single-string-to-array/31188918#31188918) – Arthur Rey Jun 28 '22 at 16:30

1 Answers1

-2

you don't need any fansy custom converters in your case. Just try this

public class Something
{
    [JsonPropertyName("items")]
    public object _items
    {
        get
        {
            return Items;
        }

        set
        {

            if (((JsonElement)value).ValueKind.ToString() == "Array")
            {
                Items = ((JsonElement)value).Deserialize<Item[]>();
            }
        }
    }

    [System.Text.Json.Serialization.JsonIgnore]
    public Item[] Items { get; set; }
}

and if you don't need to serialize it back, you can even remove _items get at all

Serge
  • 40,935
  • 4
  • 18
  • 45