How to include null value in the JSON via NSJSONSerialization?

ymotov picture ymotov · Dec 17, 2012 · Viewed 13.5k times · Source

I think I get it how to use the NSJSONSerialization over all. The call I am making is:

[NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error]

where parameters is a NSDictionary which includes keys and values to use in the JSON request. Everything is fine and all, until I have to use null as a value instead of an empty string. I can't find a way to set the value as null at all. The example of json that I need to create is:

{"target"
  {"firstname":<firstname>,
   "lastname":<lastname>},
 "error":null
}

The way server is setup is that it's expecting either an error as a string or a null if there's no error.

Any ideas? Am I missing an API call or something like that?

Thanks!

Answer

Gabriele Petronella picture Gabriele Petronella · Dec 17, 2012

You have to use NSNull. For instance

Swift

let dict = ["firstKeyHasValue": 2342, "secondKeyHasNoValue": NSNull()]

Objective-C

NSDictionary *dict = @{ @"error": [NSNull null] };

From the official documentation of NSDictionary:

Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull.