我有这样的 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:]: unrecognized selector sent to instance 0x5a9afa0 with NSDictionary *element = (NSDictionary *) [rows objectForKey:@"elements"];
我想获取距离键的值!
最佳答案
如果你仔细观察,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);
关于 Objective-C : How to read JSON in JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7802445/