I am having a really hard time extracting a single value I need from a JSON file I get from a Google Directions request.
After sending the request, I get something like that:
{
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 31.831330,
"lng" : 34.834710
},
"southwest" : {
"lat" : 31.25299000000001,
"lng" : 34.653460
}
},
"copyrights" : "Map data ©2012 Mapa GISrael",
"legs" : [
{
"distance" : {
"text" : "85.6 km",
"value" : 85613",
},
But the only thing I want is the distance value (routes/legs/distance/value),
does any one know how to extract this value from the JSON file?
First of all, that doesn’t seem like well formatted JSON, there is a trialing ” after the value of the distance.
Most JSON frameworks will give you the objects in the most appropriate type. Dictionaries will be converted to NSDictionary and a list will be converted to an NSArray.
To get the route distance in the above JSON you’d parse the JSON into an NSDictionary using one of the many libraries out there, then you’d do something like this:
NSNumber *distance = [[[[[[parsedDict objectForKey:@”routes”] objectAtIndex:0] objectForKey:@”legs”] objectAtIndex:0] objectForKey:@”distance”] objectForKey@”value”];
See if that works.