0

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.

3
  • You say you got an error with your code. Can you post the relevant code? Commented Oct 12, 2017 at 18:49
  • 2
    Deserialize it the same way each time, then just check if your List is empty or not afterwards Commented Oct 12, 2017 at 18:50
  • I would think that the JSON deserializer from NewtonSoft would handle this just fine. It would give you an array with length 0. Commented Oct 12, 2017 at 18:50

1 Answer 1

3

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>();
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.