0

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

hackdev
  • 402
  • 3
  • 8
  • 1
    The only thing `JObject.FromObject` could return in this case would be `null`, and instead it throws an exception. If you actually were to get back a `JObject`, you would have an empty JSON object, which is different. So `JObject.FromObject(null)` should be translated to just `null`, and you can't call `ToString` on that. Basically, you're in a sort of edge case here. – Lasse V. Karlsen Mar 16 '20 at 12:29
  • Since the various J* types are classes, the special case of `null` is not handled by an instance of any of those types, but instead just a reference of `null`. – Lasse V. Karlsen Mar 16 '20 at 12:29
  • In essence, there is no way to represent `null` objects with a `JObject`, because the smallest `JObject` instance you could possibly have is an empty object, which is not the same as `null`. – Lasse V. Karlsen Mar 16 '20 at 12:30
  • Thank you for your help! Let me ask something else, I believe `"null"` is valid json, correct? It seems to be according to https://stackoverflow.com/a/39124954/750124 So, how is that json/string represented in json.net? – hackdev Mar 16 '20 at 13:35
  • See Brians answer below. You don't do it with `JObject`. – Lasse V. Karlsen Mar 16 '20 at 14:48
  • Yeah, I saw the JValue but I wanted a JObject. But it's ok, in the end I realized that I had to use JObject or null, instead of representing the null in the JObject. It makes me change a dll that I didn't want to, but I'll survive. Thanks so much for everyone's help. :) – hackdev Mar 16 '20 at 15:57

2 Answers2

3

To represent a null value with a JToken, you can use JValue.CreateNull().

JToken token = JValue.CreateNull();
string json = token.ToString();
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
0

If, like me, you are just trying to cast an object that may or may not be null to a JToken, you can use the implicit value conversion operators by just casting it to JToken.

JObject obj = new JObject();
string s = null;
int? i = null;
obj.Add("s", (JToken)s);
obj.Add("i", (JToken)i);
var serialized = obj.ToString(Formatting.Indented);
muusbolla
  • 637
  • 7
  • 20