How to parse the geolocation json from google for lng and lat in objective-c
I'm creating a web request to pull lng and lat data based on zip (using the following url)
http://maps.google.com/maps/geo?q=50266
Doing so I get back the following json
{
"name": "50266",
"Status": {
"code": 200,
"request": "geocode"
},
"Placemark": [ {
"id": "p1",
"address": "West Des Moines, IA 50266, USA",
"AddressDetails": {
"Accuracy" : 5,
"Country" : {
"AdministrativeArea" : {
"AdministrativeAreaName" : "IA",
"Locality" : {
"LocalityName" : "West Des Moines",
"PostalCode" : {
"PostalCodeNumber" : "50266"
}
}
},
"Count开发者_Python百科ryName" : "USA",
"CountryNameCode" : "US"
}
},
"ExtendedData": {
"LatLonBox": {
"north": 41.6005010,
"south": 41.5254700,
"east": -93.7347000,
"west": -93.8435030
}
},
"Point": {
"coordinates": [ -93.7353858, 41.5998115, 0 ]
}
} ]
}
What I'm trying to pull from this is simply the coordinates section. Here is my current attempt that throws and exception when I hit the last line shown below
//after I get the response I turn it into json and this is working
NSArray* json = [items JSONValue];
NSString* coords = [json objectForKey:@"Placemark.Point.coordinates"];
What I'm I missing here for a quick pull of the coordinates?
The overall value return is not an array, it's a dictionary. Note that the first character is {
. If it were an array, it would be [
.
NSDictionary * json = [string JSONValue];
Now, you want the stuff under the "Placemarks" key. Note that this returns an array, since the character after the "Placemarks" key (and colon) is a [
.
NSArray * placemarks = [json objectForKey:@"Placemark"];
From this array, you want the first element, which is another NSDictionary
:
NSDictionary *firstPlacemark = [placemarks objectAtIndex:0];
From this dictionary, you want the dictionary under the key "Point":
NSDictionary *point = [firstPlacemark objectForKey:@"Point"];
From this dictionary, you want the array under the key "coordinates":
NSArray * coordinates = [point objectForKey:@"coordinates"];
At this point, you have the array that contains 3 NSNumber
objects. Voilá!
For the advanced user, you can probably use key-value coding to get at it:
NSArray * coordinates = [json valueForKeyPath:@"Placemark[0].Point.coordinates"];
Though I wouldn't recommend that unless you clearly understand what's going on there.
That does not work. Never mind! :)
Keep in mind that "[ -93.7353858, 41.5998115, 0 ]" is not a string
精彩评论