Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if dynamic is empty.

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
like image 705
jamesrom Avatar asked Jul 29 '11 01:07

jamesrom


People also ask

How check dynamic is null?

In order to check a dynamic for null, you should cast it as an object. For example, dynamic post = SomeMethod(); if (post. modified == null){ //could return errors. }

How to check empty object in html?

return Object.keys(obj).length === 0 ; This is typically the easiest way to determine if an object is empty.


1 Answers

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.

like image 129
Kazetsukai Avatar answered Oct 01 '22 07:10

Kazetsukai