0

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!

2 Answers 2

2

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"];
Sign up to request clarification or add additional context in comments.

4 Comments

don't forget about -valueForKeyPath:: [ firstResult valueForKeyPath:@"geometry.bounds.northeast" ]
@nielsbot: Note that -valueForKeyPath: is extremely inefficient.
Hey thanks! This worked perfectly! Just a question though… when I got the long_name, I alternated between NSArrays and NSDictionarys, (and that worked), why didn't that work here? (and how do I know which to use in future circumstances?)
@user1226490: If you see a [ in the JSON, it is an NSArray. If you see a {, it is an NSDictionary.
1

Check the following statement.

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.