How to check if dynamic is empty.

21,829

Solution 1

The object you get back from DeserializeObject is going to be a JObject, which has a Count property. 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 won't tell you if a dynamic object is empty, but it will tell you if a deserialized JSON object is empty.

Solution 2

You can also check with following code:

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

That worked for me.

Share:
21,829
jamesrom
Author by

jamesrom

Updated on September 16, 2021

Comments

  • jamesrom
    jamesrom over 2 years

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

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

    How can I check that output is empty? An example test case:

    var output = JsonConvert.DeserializeObject<dynamic>("{ }");
    Assert.IsNull(output); // fails
    
  • Kirk Woll
    Kirk Woll almost 13 years
    According to the docs, DeserializeObject returns T, which will not be a JObject.
  • James Newton-King
    James Newton-King almost 13 years
    dynamic is not an actual type so Json.NET falls back to using JObject.
  • Hilton Giesenow
    Hilton Giesenow almost 4 years
    I had to do something similar today and this helped, but I needed to adjust it to: ((JToken)output).Count()