开发者

How to check if dynamic is empty.

开发者 https://www.devze.com 2023-03-23 13:01 出处:网络
I am using Newtonsoft开发者_JAVA百科\'s Json.NET to deserialize a JSON string: var output = JsonConvert.DeserializeObject<dynamic>(\"{ \'foo\': \'bar\' }\");

I am using Newtonsoft开发者_JAVA百科'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


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.


You can also check with following code:

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

That worked for me.


You can just have a string conversion and check if its equal to "{ }".

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

if (output.ToString() =="{ }")
{
    // The object is empty
}
0

精彩评论

暂无评论...
验证码 换一张
取 消