Search code examples
iosobjective-cjsonsbjson

How to read json in iOS using sbjson


I am trying to read the following json:

[{"result":"1","msg":"Login Successful.”,”title":"Login","redirect":"index.php","servers":"{\"140\":\"10 minute Email\"}","server”:”xxx.xxx.xxx.xxx”}]

like so:

 NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                NSLog(@"Response ==> %@", responseData);
                
                SBJsonParser *jsonParser = [SBJsonParser new];
                NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
                NSLog(@"%@",jsonData);
                NSInteger success = [(NSNumber *) [jsonData objectForKey:@"result"] integerValue];
                NSLog(@"%d",success);
                if(success == 1)
                {
                    NSLog(@"Login SUCCESS");
                    [self alertStatus:@"Logged in Successfully." :@"Login Success!"];
                    
                } else {
                    
                    NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
                    [self alertStatus:error_msg :@"Login Failed!"];
                }

but I am getting the following error:

2014-01-01 20:44:08.857 Server Monitor[9704:70b] -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x8e59950

2014-01-01 20:44:08.857 Server Monitor[9704:70b] Exception: -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x8e59950

I think the problem is that the json is an array, how can I handle that?


Solution

  • The problem is your JSON's root object is an array:

    [ … ]
    

    but you're incorrectly assuming it's a dictionary:

    NSDictionary *jsonData = (NSDictionary *)[jsonParser objectWithString:responseData error:nil];
    

    You could do something like this if the response will always be an array with one object:

    NSArray *jsonArray = (NSArray *)[jsonParser objectWithString:responseData error:nil];
    NSDictionary *jsonData = [jsonArray lastObject];
    

    But a safer approach is to inspect the class:

    NSObject *object = [jsonParser objectWithString:responseData error:nil];
    if ([object isKindOfClass:[NSArray class]]) {
        // it's an array …
    } else if ([object isKindOfClass:[NSDictionary class]]) {
        // it's a dictionary …
    }
    

    Finally,

    • You should probably use NSJSONSerialization instead of SBJSON.
    • You should not pass nil in for the error argument; you should add error handling.