我可以解决的connectionDidFinishLoading错误

时间:2012-10-30 02:40:31

标签: ios json nsdictionary nsjsonserialization nsmutabledata

我有一个简单的JSON数组,它是从传递给第三方服务的邮政编码返回的。

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

尝试反序列化结果时出现未知错误,我不确定会出现什么问题。

这是我的connectionDidFinishLoading方法,它作为anticiapated触发但总是失败...我在最后的其他地方得到错误。想法?

-(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.");
}
}

1 个答案:

答案 0 :(得分:2)

我认为你正在使用错误的服务 - 应该是... findNearbyPostalCodesJSON ....就我从他们的网站上所知道的那样使用JSON服务。这是他们的示例网址:

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