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?
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];
}
+[NSNumber numberWithBool:] is the typical way to add a boolean to a NSDictionary.
With Objective-C literals, [NSNumber numberWithBool:YES] can be represented with just @YES,
You can create your dictionary like so:
NSDictionary *jsonDict = @{@"key":@YES};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With