Parse json with NSJSONSerialization class using objectForKey in iOS

Ali picture Ali · Jul 31, 2012 · Viewed 17.8k times · Source

I am new in iOS development. I use this code to connect to my REST Web Service and fetch data in Json format.

    NSString *url=@"URL_Address";

    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    NSURLResponse *resp = nil;
    NSError *err = nil;

    NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err];

//    NSString * theString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
//    NSLog(@"response: %@", theString);

    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: response options: NSJSONReadingMutableContainers error: &err];

    if (!jsonArray) {
        NSLog(@"Error parsing JSON: %@", err);
    } else {
        for(NSDictionary *item in jsonArray) {
            NSLog(@" %@", item);
            NSLog(@"---------------------------------");
        }
    }

Now I want to seperate them via objectForKey. I used this code inside the loop :

NSString *name = [item objectForKey:@"name"];

It does not work. I got this error:

2012-07-31 12:48:38.426 LearningAFNetworking[390:f803] -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x6844460
2012-07-31 12:48:38.428 LearningAFNetworking[390:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x6844460'
*** First throw call stack:
(0x13c8022 0x1559cd6 0x13c9cbd 0x132eed0 0x132ecb2 0x2f40 0x2bf8 0xd9a1e 0x38401 0x38670 0x38836 0x3f72a 0x290b 0x10386 0x11274 0x20183 0x20c38 0x14634 0x12b2ef5 0x139c195 0x1300ff2 0x12ff8da 0x12fed84 0x12fec9b 0x10c65 0x12626 0x254d 0x24b5 0x1)
terminate called throwing an exception(lldb)

can you help me?

Answer

user1388320 picture user1388320 · Jul 31, 2012

You have to access the 0 item of item array:

NSArray *mainArray = [item objectAtIndex:0];
(NSDictionary *obj in mainArray) {
     NSString *name = [obj objectForKey:@"name"];
}

When you got this error: -[__NSArrayM objectForKey:], you need to realize that the object that you're trying to access isn't a dictionary. It's an array (__NSArrayM), so you have to first access the 0 index, and then starting exploring the dictionary.

Take a look at this amazing tutorial, from Ray Wenderlich, that explains everything about crashes.