开发者

How to check if dynamic is empty.

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜