crowhill crowhill - 2 months ago 18
ASP.NET (C#) Question

Check if JToken is empty array

I have the following, after receiving a response from an API:

JObject goatHerd = JObject.Parse(responseString);
JToken goat = goatHerd["value"];


Now
goat
will either contain an array of data, or it will be an empty array. How can I check for empty?

I tried something like this:

if(goat != null){}


Unfortunately,
goat
actually equals
{[]}
according to Visual Studio.

I can't do:

if(goat.length != 0){}


Because
.length
doesn't work with
JToken
.

Thanks for any help.

Answer

You can use the HasValues property:

if (goat.HasValues) {}

In addition, JToken supports LINQ operations, so you can also use Any().

if (goat.Any()) {}