Monday, 27 February 2017

[Newtonsoft] Checking for null valued keys in parsed JObject

Using Newtonsoft's Json package, when we need to parse a string to get a JObject, we can do it as follows:

JObject o = JObject.Parse(serializedJsonString);
 
This is of course the case when you don't have a model class for the Json response coming in. For keys that can have a null value, checking for null values as follows is intuitive.

o["key"] == null

However, it is also incorrect. Due to the way in which null values are stored in the parsed object, the proper way of checking for null valued keys is as follows:

o["key"].Type == JTokenType.Null
 
Of course, you should do both checks and the former check should be done earlier to ensure that the key exists before checking whether the value is null.

1 comment:

jrp said...

Hi,

I would like to know, how this library is treating empty values, like ''?
Is it by default null? if you are storing this empty values anywhere, how are you storing these values? as empty string or NULL?