Search code examples
iosobjective-cgoogle-maps-sdk-ios

Is it possible to search JSON data for a specific key?


I'm using Google Maps Geocoding API in conjunction with Google Places Autocomplete API for iOS to search for addresses and return a zip code. When the JSON Data is returned, I store it in an NS Dictionary and then use a conditional to check the number of components returned. In my first test address, the zipcode is returned at index 8 within the address_components, so I was using the following conditional:

if ([[[[json objectForKey: @"results"]objectAtIndex:0] objectForKey:@"address_components"] count]>=8) {
//stuff
}

On my second test address, however, the zipcode is at index 7. Instead of trying to modify my conditional to account for every possible way that the json data could be returned, is it possible for me to search the json data for a zip-code specifically before returning anything? The json data for the zipcode (within the address components key) looks like this:

{
"long_name" = 20001;
"short_name" = 20001;
 types =   (
"postal_code"
     );

Is there a way for me to search for the "postal_code" type and return the "long_name" for it? Alternatively, is it possible to write a Geocoding API call that returns ONLY the zipcode if it exists?


Solution

  • Here's your postal codes:

    for (NSDictionary *component in json[@"results"][0][@"address_component"]) {
      if ([component[@"types"] containsObject:@"postal_code"]) {
        return component[@"long_name"];
      }
    }