ymotov ymotov - 1 year ago 82
iOS Question

How to include null value in the JSON via NSJSONSerialization?

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:


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?


Answer Source

You have to use NSNull. For instance


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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download