Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: How to put boolean values in JSON dictionary?

I could not find out how to insert a boolean value (to appear as key:true in the JSON string) in my NSDictionary:

NSMutableDictionary* jsonDict = [NSMutableDictionary dictionary];
[jsonDict setValue: YES forKey: @"key"];

The code above does not run (obviously because YES is not an object).
How can I accomplish this?

like image 959
robject Avatar asked Oct 19 '10 17:10

robject


3 Answers

You insert booleans into a dictionary using NSNumber. In this case, you can use the literal expression @YES directly, together with a dictionary literal, to make this a one-liner:

NSDictionary *jsonDict = @{@"key" : @YES};

To encode it to JSON, use +[NSJSONSerialization dataWithJSONObject:options:error]:

NSError *serializationError;
NSData *jsonData = [NSJSONSerialization
                    dataWithJSONObject:jsonDict
                    options:0 error:&serializationError];
if (!jsonData) {
    NSLog(@"%s: error serializing to JSON: object %@ - error %@",
          __func__, jsonDict, serializationError];
}
like image 67
Jeremy W. Sherman Avatar answered Sep 22 '22 16:09

Jeremy W. Sherman


+[NSNumber numberWithBool:] is the typical way to add a boolean to a NSDictionary.

like image 41
Shawn Craver Avatar answered Sep 18 '22 16:09

Shawn Craver


With Objective-C literals, [NSNumber numberWithBool:YES] can be represented with just @YES,

You can create your dictionary like so:

    NSDictionary *jsonDict = @{@"key":@YES};
like image 35
Cameron E Avatar answered Sep 18 '22 16:09

Cameron E