ka-hn
ka-hn

Reputation: 65

C# JSON; Deserialize array that sometimes has an empty value (not null)

I'm trying to deserialize a JSON response and I want a function that detects if the array is empty and if it is not empty I want it to return the values.

The JSON array looks like this when empty:

{"metrics":[]}

And when it is not empty it can look like any of the below:

{"metrics":["flow"]}

{"metrics":["energy"]}

{"metrics":["flow","energy"]}

How can I detect this?

It does not work with NullValueHandling since if the array is empty it is not null, it doesn't have any values at all.

I jus get an error about index is not found.

I am returning the array as a List in my classes.

Upvotes: 0

Views: 1333

Answers (1)

gunr2171
gunr2171

Reputation: 17579

Assuming you're using Newtonsoft.Json for deserializing the json:

class Data
{
    public List<string> Metrics { get; set; }
}

var json = "{\"metrics\":[]}";
var obj = JsonConvert.DeserializeObject<Data>(json);

obj.Metrics will be an empty collection, not null.

Plus, even if it was, you could access it like

var metrics = obj.Metrics ?? new List<string>();

Upvotes: 3

Related Questions