27

I have a JSON response from a web server that looks like this:

{"success":true, "token":"123456"}

and I want to use that in an if statement, and compare it with "YES".

However, doing this doesn't work:

NSDictionary *response = [response JSONValue]; // the JSON value from webservice response, converted to NSDictionary

if ([response objectForKey:@"success"]){} // does not work
if ([response objectForKey:@"success"] == YES){} // does not work
if ([[response objectForKey:@"success"] integerValue] == YES) {} // does not work...erroneous probably

How can I work around this? Typecasting in Boolean yields a warning too

yretuta
  • 7,963
  • 17
  • 80
  • 151

2 Answers2

61

since [response objectForKey:@"success"] does not work, what happens when you try [response valueForKey: @"success"]?

I suspect it returns a NSNumber and then you can do something like:

NSNumber * isSuccessNumber = (NSNumber *)[response objectForKey: @"success"];
if([isSuccessNumber boolValue] == YES)
{
    // this is the YES case
} else {
    // we end up here in the NO case **OR** if isSuccessNumber is nil
}

Also, what does NSLog( @"response dictionary is %@", response ); look like in your Console? I see the JSON library you're using does return NSNumber types for objectForKey, so I suspect you might not have a valid NSDictionary.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • You're missing the `@` symbol before the first argument of `NSLog` – Koen. Jun 03 '12 at 20:04
  • You may want to actually test the type instead of doing a simple cast, or put this code in a try/catch block. Otherwise, if the JSON changes, you may accidentally send `boolValue` to an NSString (which will return `YES` for "Y", "y", "T", "t", or a digit 1-9), or a collection object, which will throw an exception. – Aaron Brager May 07 '13 at 19:02
  • this solution is not effective and is long. the short answer is if([response objectForKey: @"success"] boolValue]) – hkaraoglu Feb 02 '16 at 15:16
11

An alternative approach to this, which requires no conversion to NSNumber is something like below:

if ([response objectForKey:@"success"])
{
    if ([[response objectForKey:@"success"] boolValue])
        NSLog(@"value is true");
}
Scott D
  • 1,394
  • 1
  • 13
  • 17