Я использую библиотеку TouchJSON, доступную здесь
https://github.com/TouchCode/TouchJSON
, чтобы сделать что-то одно в строках:
// For the purpose of this example, use stringWithContentsOfURL
NSString *googleURL = @"http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&sensor=false";
NSURL *url = [NSURL
URLWithString:[googleURL
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error = NULL;
NSString *theJSONString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@", theJSONString);
// Parse with TouchJSON
NSDictionary *replyDict = [NSDictionary dictionaryWithJSONString:theJSONString error:&error];
NSString *distanceString = [[[[[[replyDict objectForKey:@"rows"] objectAtIndex:0]
objectForKey:@"elements"]
objectAtIndex:0]
objectForKey:@"distance"]
objectForKey:@"value"];
double distance = distanceString.doubleValue;
NSLog(@"Distance: %f", distance);
NSLog(@"Error: [%@]", error.description);
, и это дает мне следующий вывод наконсоль:
{
"destination_addresses" : [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
"origin_addresses" : [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1 686 km",
"value" : 1685690
},
"duration" : {
"text" : "3 jours 21 heures",
"value" : 336418
},
"status" : "OK"
},
{
"distance" : {
"text" : "136 km",
"value" : 136478
},
"duration" : {
"text" : "6 heures 59 minutes",
"value" : 25117
},
"status" : "OK"
}
]
},
{
"elements" : [
{
"distance" : {
"text" : "1 426 km",
"value" : 1426087
},
"duration" : {
"text" : "3 jours 6 heures",
"value" : 281311
},
"status" : "OK"
},
{
"distance" : {
"text" : "251 km",
"value" : 251174
},
"duration" : {
"text" : "12 heures 6 minutes",
"value" : 43583
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
Distance: 1685690.000000
Error: [(null)]
Если вы хотите использовать вместо этого SBJson, вы можете получить его здесь
https://github.com/stig/json-framework
заменить строку
// Parse with TouchJSON
NSDictionary *replyDict = [NSDictionary dictionaryWithJSONString:theJSONString error:&error];
с
// Parse with SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *replyDict = [parser objectWithString:theJSONString];
Не забудьте включить соответствующую библиотеку в ваш файл .h