Search code examples
iosjsonafnetworkingafjsonrequestoperation

How to parse JSON multi-array


I need to parse the JSON file provided by Google Maps API Then i use the AFNetworkingRequestHow to get the JSON response. I built this dictionary:

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

But now, how can i reach the first value field of duration tag?

JSON File to parse:

{
"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"
         }
      ]
   }   
}

Solution

  • Try

    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];