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

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


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};