5

How do I get true/false (instead of "true"/"false") in json from a NSDictionary using NSJSONSerialization dataWithJSONObject? What keys should I store in the dictionary to get that?

Boon
  • 40,656
  • 60
  • 209
  • 315
  • This is the one area where mapping between JSON and Objective-C objects is slightly less than perfect, but generally `@YES`/`@NO` will work, as stated below. Do note, though that this has nothing to do with "keys". The keys in a dictionary/JSON "object" need to be strings. It's the *values* we're talking about. – Hot Licks Mar 14 '14 at 17:26
  • 1
    @Daij-Djan Stop the harassment please. – Boon Mar 14 '14 at 18:53
  • possible dupe of http://stackoverflow.com/questions/13615451/how-do-i-get-nsjsonserialization-to-output-a-boolean-as-true-or-false – Daij-Djan Mar 14 '14 at 19:06

1 Answers1

9

NSNumber objects containing a BOOL are mapped to JSON "true" and "false". So just use @YES, @NO, or generally @(someBOOL). For example:

NSDictionary *dict = @{@"this is": @YES};
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// {"this is":true}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    Why is NSJSONSerialization able to distinguish between @YES vs @(1) and output true for former and 1 for latter? – Boon Mar 14 '14 at 16:57
  • 2
    @Boon: It probably uses the `objCType` method to get information about the type of the value. – Martin R Mar 14 '14 at 16:58
  • 3
    @Boon Add code like this: `NSNumber *aBool = @YES; NSNumber *anInt = @1;`. Now use the debugger to look at the internal types generated by those two lines. You actually get two different internal types for those two objects. – rmaddy Mar 14 '14 at 17:00