0

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"
         }
      ]
   }   
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Victor Casé
  • 745
  • 8
  • 15
  • Check [here the technique](http://stackoverflow.com/questions/14958883/ios-serialize-deserialize-complex-json-generically-from-nsobject-class/16771574#16771574) that is more generic and less error prone. – Alphapico Jun 03 '13 at 06:54

3 Answers3

1

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];
Anupdas
  • 10,211
  • 2
  • 35
  • 60
0
[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.

Nimit Parekh
  • 16,776
  • 8
  • 50
  • 72
0

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];
manujmv
  • 6,450
  • 1
  • 22
  • 35