1

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?

Robert Segdewick
  • 543
  • 5
  • 17
  • 5
    JObject are dictionaries, you can look at the Count properties, which would be 0 if the object is empty. – Jazzwave06 Nov 25 '19 at 18:40
  • You can use `JsonExtensions.IsNullOrEmpty()` from [this answer](https://stackoverflow.com/a/24067483) to [Checking for empty/null JToken in a JObject](https://stackoverflow.com/q/24066400). In fact this looks like a duplicate, agree? – dbc Nov 25 '19 at 23:16

2 Answers2

3

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
}
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
0

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.
gunr2171
  • 16,104
  • 25
  • 61
  • 88
  • For 1 you can just use string.Replace instead of trim – DetectivePikachu Nov 25 '19 at 19:07
  • @DetectivePikachu true, problem is that you'll need to replace every whitespace unicode character, and that's such an edge case that I don't want to get into it. – gunr2171 Nov 25 '19 at 19:08
  • @gunr2171, OP does not want to check that root node is empty or not. He is trying to check JObject `jsonObject.content.important` contains any `JToken` or not. Kindly check OP's code `dynamic content = jsonObject.content.important;` – Prasad Telkikar Nov 25 '19 at 19:32
  • 1
    @PrasadTelkikar you're totally correct. Didn't realise that myself until much after I posted this. Uh, I'll leave this post here for a bit longer than probably delete it later. – gunr2171 Nov 25 '19 at 19:34