我需要解析Google Maps API提供的JSON文件然后我使用AFNetworkingRequestHow来获取JSON响应。我制作了这本字典:
NSDictionary *jsonDict = (NSDictionary *) JSON;
NSArray *rows = [jsonDict objectForKey:@"rows"];
但是现在,我如何才能达到duration标签的第一个值字段?
要解析的JSON文件:
{
"destination_addresses" : [ "San Francisco, CA, USA", "Victoria, BC, Canada" ],
"origin_addresses" : [ "Vancouver, BC, Canada", "Seattle, WA, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,527 km",
"value" : 1527251
},
"duration" : {
"text" : "15 hours 0 mins",
"value" : 54010
},
"status" : "OK"
},
{
"distance" : {
"text" : "112 km",
"value" : 111906
},
"duration" : {
"text" : "3 hours 1 min",
"value" : 10885
},
"status" : "OK"
}
]
}
}
尝试
NSDictionary *jsonDict = (NSDictionary *) JSON;;
NSArray *rows = jsonDict[@"rows"];
NSDictionary *row = rows[0];
NSArray *elements = row[@"elements"];
NSDictionary *element = elements[0];
NSDictionary *duration = element[@"duration"];
NSInteger value = [duration[@"value"] integerValue];
[json objectForKey:@"elements"]
是NSArray。不能使用数组直接初始化NSDictionary。
(在JSON中,{和}表示键值对,如NSDictionary,而[和]分隔排序列表,如NSArray,这就是为什么映射是按原样进行的…(
以下想法可以让你理解开发时间,因此可能会有很大帮助。
您可以使用以下代码:
NSString *valueString = [[[[[rows objectAtindex:0]objectForKey:@"elements" ]objectAtindex:0]objectForKey:@"duration"] objectForKey:@"value"];
//if you want integer value
NSInteger value = [valueString integerValue];