0

我需要解析Google Maps API提供的 JSON 文件 然后我使用 AFNetworkingRequestHow 来获取 JSON 响应。我建立了这本字典:

    NSDictionary *jsonDict = (NSDictionary *) JSON;
    NSArray *rows = [jsonDict objectForKey:@"rows"];

但是现在,我怎样才能到达持续时间标签 的第一个字段?

要解析的 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"
         }
      ]
   }   
}
4

3 回答 3

1

尝试

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];
于 2013-06-03T06:21:26.173 回答
0
[json objectForKey:@"elements"]

是一个 NSArray。您不能直接使用数组初始化 NSDictionary。

(在 JSON 中,{ 和 } 表示键值对,如 NSDictionary,而 [ 和 ] 分隔有序列表,如 NSArray,这就是映射按原样完成的原因......)

以下认为您可以了解开发时间,因此可能会有所帮助。

于 2013-06-03T06:18:12.720 回答
0

您可以使用以下代码:

NSString *valueString = [[[[[rows objectAtindex:0]objectForKey:@"elements" ]objectAtindex:0]objectForKey:@"duration"] objectForKey:@"value"];

//if you want integer value
NSInteger value = [valueString integerValue];
于 2013-06-03T06:25:30.147 回答