Reputation: 593
I'd like to check if the json object deserialized using Newtonsoft is empty. I am using this code which feels a little hacky:
try{
dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);
dynamic content = jsonObject.content.important;
if (((JObject)content).ToString() != "{}"){ // inspecting if "imporant" has value
// do stuff
}
}catch(Exception e){
// handle error
}
Is there a more "stylist" approach to inspecting if object exists?
Upvotes: 1
Views: 4662
Reputation: 16079
You can check count of JTokens
available in JObject content
. It will return 0
, if JObject
is empty. Like,
try
{
dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);
dynamic content = jsonObject.content.important;
if (((JObject)content).Count > 0){ // inspecting if "imporant" has value
// do stuff
}
}
catch(Exception e)
{
// handle error
}
Upvotes: 3
Reputation: 17579
Just check the content of the jsonString
string variable before you deserialize it. You're overcomplicating things by deserializing, then serializing, then comparing.
A JSON object always starts and ends with {
/ }
, and if you mean that an "empty" object is an object that has no properties within, then you're checking if the string value is equal to {}
.
if (jsonString.Trim() == "{}")
{
// object is empty
}
else
{
// do deserialization
}
The Trim()
is put in just in case there is whitespace surrounding the brackets.
Note you'll have 2 edge cases here:
Upvotes: 0