Search code examples
iosjsonsbjson

iOS NSDictionary value determine if Boolean from JSON boolean


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


Solution

  • 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.