In newtonsoft json.net when we use
JsonConvert.SerializeObject(null, Formatting.Indented)
I get "null" in the output as expected.
Now, I would like to represent objects (which can be null) with a JObject, but it throws an exception when I try to encode null this way:
(JObject.FromObject(null)).ToString(Formatting.Indented)
Is there a way to do this? Thanks
JObject.FromObjectcould return in this case would benull, and instead it throws an exception. If you actually were to get back aJObject, you would have an empty JSON object, which is different. SoJObject.FromObject(null)should be translated to justnull, and you can't callToStringon that. Basically, you're in a sort of edge case here.nullis not handled by an instance of any of those types, but instead just a reference ofnull.nullobjects with aJObject, because the smallestJObjectinstance you could possibly have is an empty object, which is not the same asnull."null"is valid json, correct? It seems to be according to stackoverflow.com/a/39124954/750124 So, how is that json/string represented in json.net?JObject.