Using Boolean Values with TouchJSON

When cre­at­ing an NSDictionary to seri­al­ize as JSON with TouchJSON you can’t set a BOOL value in the dic­tion­ary because it requires an object.

Use an NSNumber, which will be con­ver­ted to true or false by the TouchJSON library.

Eg:

 
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:[NSNumber numberWithBool:YES forKey:@"shouldBeOn"];
[dictionary setObject:[NSNumber numberWithBool:NO forKey:@"shouldBeOff"];
NSError *error = NULL;
NSData *jsonData = [[CJSONSerializer serializer] serializeObject:dictionary error:&error];
 

Produces:

{
    "shouldBeOn": true,
    "shouldBeOff": false
}

Post a Comment

Your email is never shared.