Using Newtonsoft's Json package, when we need to parse a string to get a JObject, we can do it as follows:
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.
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:
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.
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.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
JObject o1 = JObject.Parse(@"{
'key1' : null,
'key2':{}
}");
System.Console.WriteLine(o1["key1"].Type == JTokenType.Null); // this is true
System.Console.WriteLine(o1["key3"] == null); // this is true too
So, search for a key returning a null means that particular key is not there in the json.