我有这样的JSON:
{
"destination_addresses" : [ "Dimitrov, Phnom Penh, Cambodia" ],
"origin_addresses" : [ "Tchecoslovaquie, Phnom Penh, Cambodia" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "0.6 km",
"value" : 594
},
"duration" : {
"text" : "2 mins",
"value" : 100
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
这是我的代码:
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:apiResponse error:nil];
NSLog(@"Data = %@",data);
// getting the data from inside of "rows"
NSDictionary *rows = (NSDictionary *) [data objectForKey:@"rows"];
NSLog(@"Row = %@",rows);
NSDictionary *element = (NSDictionary *) [rows objectForKey:@"elements"];
NSLog(@"elements = %@",element);
NSDictionary *distance = (NSDictionary *) [rows objectForKey:@"distances"];
NSLog(@"Distance = %@",distance);
但收到错误:
- [__ NSArrayM objectForKey:]:使用NSDictionary * element =(NSDictionary)将无法识别的选择器发送到实例0x5a9afa0 *)[rows objectForKey:@“elements”];
我希望在距离键中获得值!
答案 0 :(得分:2)
如果仔细观察,rows
是数组中的字典。
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "0.6 km",
"value" : 594
},
"duration" : {
"text" : "2 mins",
"value" : 100
},
"status" : "OK"
}
]
}
]
所以你需要做
NSArray *rows = [data objectForKey:@"rows"];
NSDictionary *rowsDict = [rows objectAtIndex:0];
NSArray *element = [rowsDict objectForKey:@"elements"];
NSLog(@"elements = %@",element);
NSDictionary *distance = [[element objectAtIndex:0] objectForKey:@"distances"];
NSLog(@"distance= %@", distance);
所以&等等。
NSLog(@"Distance = %@",distance);