How to check if dynamic is empty.

I am using Newtonsoft Json.NET to deserialize a JSON string:

var output = JsonConvert.DeserializeObject<dynamic>("{ 'foo': 'bar' }");

How can I check that is outputempty? Test Case Example:

var output = JsonConvert.DeserializeObject<dynamic>("{ }");
Assert.IsNull(output); // fails
+5
source share
2 answers

The object you return from DeserializeObject will be a JObject that has a property Count. This property tells you how many properties are on the object.

var output = JsonConvert.DeserializeObject<dynamic>("{ }");

if (((JObject)output).Count == 0)
{
    // The object is empty
}

This will not tell you that the dynamic object is empty, but it will tell you if the deserialized JSON object is empty.

+12
source

You can also check with the following code:

var output = JsonConvert.DeserializeObject<dynamic>("{ }");
if (output as JObject == null)
{
}

It worked for me.

+2
source

All Articles