How to include null value in the JSON via NSJSONSerialization?

14,789

Solution 1

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.

Solution 2

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"]
Share:
14,789
ymotov
Author by

ymotov

Updated on June 04, 2022

Comments

  • ymotov
    ymotov almost 2 years

    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!