Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS NSDictionary value determine if Boolean from JSON boolean

Tags:

json

ios

sbjson

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

like image 339
yretuta Avatar asked Nov 25 '11 08:11

yretuta


2 Answers

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.

like image 84
Michael Dautermann Avatar answered Sep 21 '22 07:09

Michael Dautermann


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");
}
like image 11
Scott D Avatar answered Sep 22 '22 07:09

Scott D