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.

2
  • This is the exact same problem as this question except the exact opposite. the solution is the same (as is my comment!) Commented Jun 28, 2022 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 Commented Jun 28, 2022 at 16:30

1 Answer 1

-1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.