Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

{"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!

like image 429
ymotov Avatar asked Dec 17 '12 03:12

ymotov


People also ask

How do I allow null values in JSON?

To include null values in the JSON output of the FOR JSON clause, specify the INCLUDE_NULL_VALUES option. If you don't specify the INCLUDE_NULL_VALUES option, the JSON output doesn't include properties for values that are null in the query results.

Can we have NULL value in JSON?

JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

Can a JSON object have a null key?

JSON has two types of null value In JSON there are effectively two types of null . When the key is provided, and the value is explicitly stated as null . When the key is not provided, and the value is implicitly null .


1 Answers

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.

like image 61
Gabriele Petronella Avatar answered Sep 23 '22 23:09

Gabriele Petronella