Question

I have a simple JSON array that is returned from a zip code passed to a third party service.

http://api.geonames.org/findNearbyPostalCodes?postalcode=94115&country=US&radius=5&username=frequentz

I get an unknown error when trying to deserialize the results and I'm not sure what is going wrong.

Here is my connectionDidFinishLoading method, which fires as anticiapated but always fails...and I get the error in the last else if. Ideas?

-(void) connectionDidFinishLoading:(NSURLConnection *)connection {

NSLog(@"connectionDidFinishLoading...");

self.zipCodes = [NSMutableArray array];

NSError *error = nil;

id jsonObject = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingAllowFragments error:&error];

if (jsonObject != nil && error == nil) {

    NSLog(@"Successfully deserialized...");

    if ([jsonObject isKindOfClass:[NSDictionary class]]) {

        NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
        NSLog(@"Deserialized JSON Dictionary = %@", deserializedDictionary);

        for (NSDictionary *item in jsonObject) {

          NSString *city = [item objectForKey:@"adminName2"];
          NSString *stateAbbreviation = [item objectForKey:@"adminCode1"];
          NSString *postalCode = [item objectForKey:@"postalCode"];
          NSString *distance = [item objectForKey:@"distance"];
          NSString *country = [item objectForKey:@"country"];
          NSString *stateName = [item objectForKey:@"stateName"];

          ZipCodes *zipCode = [[ZipCodes alloc] initWithName:city stateAbbrev:stateAbbreviation postalCode:postalCode distanceFromGPSZip:distance country:country stateFullName:stateName];

          [self.zipCodes addObject:zipCode];
        }
    }
    else if ([jsonObject isKindOfClass:[NSArray class]]){
        NSArray *deserializedArray = (NSArray *)jsonObject;
        NSLog(@"Deserialized JSON Array = %@", deserializedArray);
    }
    else {
        /* Some other object was returned. We don't know how to deal
         with this situation as the deserializer returns only dictionaries or arrays */
    }
}
else if (error != nil){
    NSLog(@"An error happened while deserializing the JSON data.");
}
}
Was it helpful?

Solution

I think you're using the wrong service --it should be ...findNearbyPostalCodesJSON.... To use the JSON service as far as I can tell from their website. This is their example URL:

http://api.geonames.org/findNearbyPostalCodesJSON?postalcode=8775&country=CH&radius=10&username=demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top