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

3
  • How are you parsing the JSON response? Commented Nov 25, 2011 at 8:17
  • the question was tagged sbjson. I am using the ios library SBJSON stig.github.com/json-framework Commented Nov 25, 2011 at 8:19
  • I forgot to highlight the code that does the parsing, sorry Commented Nov 25, 2011 at 8:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You're missing the @ symbol before the first argument of NSLog
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.
this solution is not effective and is long. the short answer is if([response objectForKey: @"success"] boolValue])
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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.