2

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

6
  • 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. Commented Mar 16, 2020 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. Commented Mar 16, 2020 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. Commented Mar 16, 2020 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 stackoverflow.com/a/39124954/750124 So, how is that json/string represented in json.net? Commented Mar 16, 2020 at 13:35
  • See Brians answer below. You don't do it with JObject. Commented Mar 16, 2020 at 14:48

2 Answers 2

5

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

JToken token = JValue.CreateNull();
string json = token.ToString();
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.