-1

I am reading data from The Joys of Code. The API returns data in JSON format where boolean variables are written as so:

{ "obj" :
   { 
      "sharing":false,
      "modified":"tuesday"
   }
}

Notice, sharing:false does not have quotation marks around the word false. I am then using NSJSONSerialization to parse this JSON into an object (NSDictionary in this example).

The problem is, "sharing":false or "sharing":true is always creating an object with sharing = 0, where 0 is an NSNumber with value 0.

My question is if this is valid JSON and NSJSONSerialization is not working correctly, or if the original JSON is invalid.

Paul de Lange
  • 10,613
  • 10
  • 41
  • 56

2 Answers2

2

NSJSONSerialization works fine for me with the above json (putting in false and true) :

NSData *json = [@"{ \"obj\" : \
                { \
                \"sharing\":false, \
                \"modified\":\"tuesday\" \
                } \
                }" dataUsingEncoding:NSUTF8StringEncoding];
id dict = [NSJSONSerialization JSONObjectWithData:json options:0 error:nil];
id sharing = dict [@"obj"][@"sharing"];
NSLog(@"%d", [sharing boolValue]);

json = [@"{ \"obj\" : \
                { \
                \"sharing\":true, \
                \"modified\":\"tuesday\" \
                } \
                }" dataUsingEncoding:NSUTF8StringEncoding];
dict = [NSJSONSerialization JSONObjectWithData:json options:0 error:nil];
sharing = dict [@"obj"][@"sharing"];
NSLog(@"%d", [sharing boolValue]);
Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
0

It is valid. You can always get BOOL from NSNumber as [number boolValue] and check it as

if ([number boolValue])

or

if ([number boolValue] == YES)
iDev
  • 23,310
  • 7
  • 60
  • 85
  • Ok so it is valid? Do you have a reference so I can query Apple about why NSJSONSerialization always maps it to NO? – Paul de Lange Dec 09 '12 at 10:03
  • @PauldeLange, It shouldn't be `NO` always.. It should be 0 for false and 1 for true. – iDev Dec 09 '12 at 10:03
  • 1
    @PauldeLange, Are you asking about technical support, https://developer.apple.com/support/technical/submit/.. Just checked few other question about bool and json and looks like my above answer should help in this situation. See this question here http://stackoverflow.com/questions/7530173/how-to-parse-json-in-ios-app.. Not sure why you are not getting true there.. – iDev Dec 09 '12 at 10:09