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.
Author by
jamesrom
Updated on September 16, 2021Comments
-
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 almost 13 years
-
James Newton-King almost 13 yearsdynamic is not an actual type so Json.NET falls back to using JObject.
-
Hilton Giesenow almost 4 yearsI had to do something similar today and this helped, but I needed to adjust it to:
((JToken)output).Count()