0

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

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

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

这是我的 connectionDidFinishLoading 方法,它按预期触发但总是失败......我在最后一个 else if 中得到错误。想法?

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

1 回答 1

2

我认为您使用了错误的服务——它应该是 ...findNearbyPostalCodesJSON...。据我从他们的网站上可以看出,要使用 JSON 服务。这是他们的示例网址:

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

于 2012-10-30T03:25:32.447 回答