Robert Segdewick
Robert Segdewick

Reputation: 593

Check if json object is exists

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

Answers (2)

Prasad Telkikar
Prasad Telkikar

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

gunr2171
gunr2171

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:

  1. If there is whitespace between the brackets this code will think it's not empty, which is wrong.
  2. This doesn't care if the string is valid JSON or not.

Upvotes: 0

Related Questions