Extracting specific part of JSON respose on iPhone
I'm looking at adding a distance calculator to my application. I have been looking at Google's API put i cant seem to decode the JSON. I have managed to do so with PHP. The code for that was:
substr($convertedtoarray['routes']['0']['legs']['0']['distance']['text'], 0, -3);
On the iPhone i managed to get the JSON response but can't get the specific part of it that I want.
Json address: http://maps.googleapis.com/maps/api/directions/json?origin=plymouth&destination=pl210bp&sensor=false
NSMutableDictionary *luckyNumbers = [responseString JSONValue];
[responseString release];
if (luckyNumbers != nil) {
NSString *responseStatus = [lu开发者_Go百科ckyNumbers objectForKey:@"routes"];'
}
Where would I go from here?
Any help would be great cheers
NSString *responseStatus = [[[[[[luckyNumbers objectForKey:@"routes"]objectAtIndex:0] objectForKey:@"legs"]objectAtIndex:0] objectForKey:@"distance"] objectForKey:@"text"];
Very ugly you can extract in separate objects like this:
NSArray *routesArray = [luckyNumbers objectForKey:@"routes"];
NSDictionary *firstRoute = [routesArray objectAtIndex:0];
NSArray *legsArray = [firstRoute objectForKey:@"legs"];
NSDictionary *firstLeg = [legsArray objectAtIndex:0];
NSDictionary *distanceDict = [firstLeg objectForKey:@"distance"];
NSString *distanceText = [distanceDict objectForKey:@"text"];
Good luck.
The easiest thing to do would be to create a dictionary iterator, and loop over what children the luckynumbers dictionary has, you can print out, or debug, to see what the keys for these children are, and what object types they are.
I used this technique a few times to figure out what the structure of an XML doc I was being returned was like.
精彩评论