Search code examples
iosobjective-cjsonnsdictionaryfor-in-loop

getting key value pairs out of NSDictionary from JSON


I'm a little new to all this and I'm having trouble getting information out of an incoming JSON NSDistionary. Heres the dictionary:

enter image description here

As a first step I'm trying to retrieve the address sections postcode, here's the code:

               for (NSString *address in jsonData [@"address"][@"postcode"]) {
                         NSLog(@"address is ===> %@", address);
                   }

However when I run this i am receiving an NSException error: 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0x79e4daf0'

Any help with this would be very much appreciated. Thanks


Solution

  • As Shown your JSON file contain an array of 3 objects, we first convert data to array. Then you have to access dictionary by using

    1.valueForKeyPath@"dictionarykey1.dictionarykey2".

    2.objectForKey@"dictionarykey1".

    NSLog(@"JSON: %@", responseObject);
    
        NSArray *Response=(NSArray*)[responseObject copy];
    
        NSString * Address=[Response[0] valueForKeyPath:@"address.postcode"];