Objective-C:如何在 JSON 中读取 JSON?
Posted
技术标签:
【中文标题】Objective-C:如何在 JSON 中读取 JSON?【英文标题】:Objective-C : How to read JSON in JSON? 【发布时间】:2011-10-18 04:31:41 【问题描述】:我有这样的 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:]: 无法识别的选择器发送到实例 0x5a9afa0 与 NSDictionary *element = (NSDictionary *) [rows objectForKey:@"elements"];
我想获得距离键值!
【问题讨论】:
【参考方案1】:如果你仔细观察,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:如何在 JSON 中读取 JSON?的主要内容,如果未能解决你的问题,请参考以下文章
在 Objective-C 中使用 JSON 数据的 NSJSONSerialization 读取 NSDictionary 集的键值