如何解析JSON多数组

时间:2013-06-03 06:14:48

标签: ios json afnetworking afjsonrequestoperation

我需要解析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"
         }
      ]
   }   
}

3 个答案:

答案 0 :(得分: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];

答案 1 :(得分:0)

[json objectForKey:@"elements"]

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

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

以下思考可以让您了解开发时间,这样可能会有所帮助。

答案 2 :(得分:0)

您可以使用以下代码:

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

//if you want integer value
NSInteger value = [valueString integerValue];