Objective-C: How to put booleans in a JSON dictionary?

I could not find out how to insert a boolean (so that it appears as key:true in the JSON string) in my NSDictionary:

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

The above code does not execute (obviously because YES is not an object).
How can i do this?

+7
json objective-c cocoa macos
source share
3 answers

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

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

To encode it in 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]; } 
+11
source share

+ [NSNumber numberWithBool:] is a typical way to add booleans to an NSDictionary.

+7
source share

With Objective-C literals [NSNumberWithBool: YES] can be represented simply by @YES,

You can create your dictionary as follows:

  NSDictionary *jsonDict = @{@"key":@YES}; 
+6
source share

All Articles