The Awesome Guy
The Awesome Guy

Reputation: 332

Parsing JSON in Objective-C

I am trying to parse the JSON at this URL:

http://maps.googleapis.com/maps/api/geocode/json?address=canada&sensor=false

in Objective-C. I'm trying to get the northeast latitude under "bounds", and this is the code I've written to try and do that (feed is an NSDictionary object):

NSArray *results = [feed objectForKey:@"results"];
NSDictionary *firstResult = [results objectAtIndex:0];
NSArray *geometry = [firstResult objectForKey:@"geometry"];
NSDictionary *firstGeo = [geometry objectAtIndex:0];
NSArray *bounds = [firstGeo objectForKey:@"bounds"];
NSDictionary *northeast = [bounds objectAtIndex:0];
NSString *neLat = [[NSString alloc] initWithString:[northeast objectForKey:@"lat"]];

Even though it compiles fine and the JSON data is valid, when I run it I get this error:

[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0xa672390 2012-02-24 01:32:06.321 Geo[570:11603] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0xa672390'

I don't know why this is happening, as I successfully got long_name before… any help is greatly appreciated :)

Thanks in advance!

Upvotes: 0

Views: 349

Answers (2)

Ilanchezhian
Ilanchezhian

Reputation: 17478

Check the following statement.

NSArray *geometry = [firstResult objectForKey:@"geometry"];

It seems for the geometry, it does not return NSArray. It returns NSDictionary

Upvotes: 1

kennytm
kennytm

Reputation: 523624

The geometry and bounds are already dictionaries.

     "geometry" : {    // <-- a dictionary!
        "bounds" : {   // <-- also a dictionary!
           "northeast" : {
              "lat" : 83.1150610,
              "lng" : -52.62040200000001
           },

So you should write

NSDictionary *geometry = [firstResult objectForKey:@"geometry"];
NSDictionary *bounds = [geometry objectForKey:@"bounds"];
NSDictionary *northeast = [bounds objectForKey:@"northeast"];

Upvotes: 2

Related Questions