How to parse JSON multi-array

630 Views Asked by At

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

There are 3 best solutions below

0
On BEST ANSWER

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];
2
On
[json objectForKey:@"elements"]

is an NSArray. You can't initialize an NSDictionary directly with an array.

(in JSON, { and } denote key-value pairs, like NSDictionary, whereas [ and ] delimit ordered lists like NSArray, that's why the mapping is done as it is...)

Following thinks can you understanding for development time so it may help lot.

0
On

You can use the following code:

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

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