Home > Software engineering >  C# System.Text.Json consider an empty object an empty array
C# System.Text.Json consider an empty object an empty array

Time:07-01

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.

CodePudding user response:

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

  • Related