34

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!

ymotov
  • 1,449
  • 3
  • 17
  • 28

4 Answers4

65

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.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
5

I tried doing this and worked for me.

var param: [String:Any] = [:]

param["firstName"] = "somename"

param["middleName"] = NSNull()

param["lastName"] = "somename"

print(param)

Result:

["firstName":"somename","middleName":null,"lastName":"somename"]
koen
  • 5,383
  • 7
  • 50
  • 89
Ashish Gupta
  • 101
  • 2
  • 4
0

If you are using Swifty JSON, I've just created a PR that should handle nil. It's not merged yet and might need some improvements. The part that describes how to do that should be a good start to write your own implementation if you need to. The logic is not that complicated but there might be tricky edge cases/performance things to think about.

I know it's not a direct response to the question since it's replacing NSJSONSerialization, but I hope it can help some people frustrated by how Swift handles nil/json!

Guig
  • 9,891
  • 7
  • 64
  • 126
-4

Just try something like this:

NSDictionary *jsonObj = [NSDictionary dictionaryWithObjectsAndKeys:@"My Name", @"name", @"Developer", @"occupation", NULL, @"My NULL field", nil];

and use this object as parameter where you want it.

Muddu Patil
  • 713
  • 1
  • 11
  • 24
Ricardo Falasca
  • 115
  • 1
  • 3