I am unsure how to parse nested JSON output. I am using Googles JSON geocoding and trying to extract the coordinates. I am thinking I need another level of parsing. My code that does not work:
hostStr = [hostStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *hostURL = [NSURL URLWithString:hostStr];
NSString *jsonString = [[NSString alloc] initWithContentsOfURL:hostURL];
self.jsonArray = [jsonString JSONValue];
NSDictionary *coordinates = [self.jsonArray objectForKey:@"id:p1"];
NSLog(coordinates);
NSString *point = [coordinates objectForKey:@"Point"];
NSLog(point);
The JSON:
{
"name": "11111 WASHINGTON AVE # 116 SAN PEDRO, CA 91111",
"Status": {
"code": 200,
"request": "geocode"
},
"Placemark": [ {
"id": "p1",
"address": "11111 Washington Ave, San Pedro, CA 91111, USA",
"AddressDetails": {
"Accuracy" : 8,
"Country" : {
"AdministrativeArea" : {
"AdministrativeAreaName" : "CA",
"Locality" : {
"LocalityName" : "San Pedro",
"PostalCode" : {
"PostalCodeNumber" : "91111"
},
"Thoroughfare" : {
"ThoroughfareName" : "Washington Ave"
}
}
},
"CountryName" : "USA",
"CountryNameCode" : "US"
}
},
"ExtendedData": {
"LatLonBox": {
"north": 37.7026153,
"south": 37.6999173,
"east": -122.1393925,
"west": -122.1420904
}
},
"Point": {
"coordinates": [ -122.1407313, 50.7012704, 0 ]
}
} ]
}
It looks like you’re unclear on how to reach into nested objects in the parsed JSON. I assume you’re using JBJson (formerly Json-Framework) to get that
JSONValuecategory on NSString, yes? If so, it’s parsed the whole deal, you just have to walk it.The first helpful this online json visualizer: http://jsonviewer.stack.hu/
Paste your raw JSON into that to see the whole tree structure of it.
Then, you should understand your’e going to to get an NSDictionary that has NSDictionaries and NSArrays in its values. So it’s not “id: p1” you’re digging into. If you want those coordinates, the coordinates array is at the path Placemark[0].Point.coordinates.
It’s going to look more like:
A clever person who has worked in Obj-c more recently than I might be able to walk that with an keypath or something, but I did it this way to show you the nested objects you’re really navigating here.