2

Objective-C enforces the conversion of a BOOL to an NSNumber for storage in an NSDictionary which is converted to JSON by NSJSONSerialization.

Is it possible to write literal boolean values (true or false with no string quotations) to JSON instead of 0 and 1? This would make interactions with servers that don't support 0 or 1 a lot easier.

For an example, if I had a boolean value being saved in an NSDictionary using @YES/@NO, [NSNumber numberWithBool:BOOL], etc. NSJSONSerialization would output it like this:

{
    "excludes": 1
}

But I want it to look like this:

{
    "excludes": true
}

Any ideas or solutions? Android makes this much easier.

afollestad
  • 2,929
  • 5
  • 30
  • 44
  • possible duplicate of [How to create true/false in JSON in Objective-C](http://stackoverflow.com/questions/22411119/how-to-create-true-false-in-json-in-objective-c) – Martin R Mar 23 '14 at 23:52
  • @MartinR same concept but the accepted answer there doesn't seem to work. – afollestad Mar 23 '14 at 23:54
  • Can you show a complete example? It worked for me when I tested it. – Martin R Mar 23 '14 at 23:55
  • @MartinR well I have a class that contains a method called "toJSON" that returns data which is passed to the serializer. It looks like this: http://pastebin.com/Q1AnJpDv, excludes is a `BOOL`. Changing that excludes line to "@"excludes": [self excludes] ? @YES : @NO};" doesn't work either. – afollestad Mar 23 '14 at 23:58
  • That is strange. I just tried it with `@{@"foo": @YES, @"bar": @NO}` and got the JSON data `{"foo":true,"bar":false}` . – Martin R Mar 24 '14 at 00:03
  • @MartinR how do you use `NSJSONSerialization` when you convert the dictionary? – afollestad Mar 24 '14 at 00:05
  • Exactly as here: http://stackoverflow.com/a/22411217/1187415. – Martin R Mar 24 '14 at 00:06
  • @MartinR oh weird, you're right. It appears that something happens in between generating the NSData and transmitting it via the AFNetworking library. – afollestad Mar 24 '14 at 00:24

0 Answers0