2012-10-30 35 views
0

我有一个简单的JSON数组,从传递给第三方服务的邮政编码返回。我可以解决的connectionDidFinishLoading错误

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

我在尝试时反序列化的结果,我不知道是怎么了未知错误。

这里是我的connectionDidFinishLoading方法,它作为anticiapated触发但总是失败......并且我在最后一个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."); 
} 
} 
+0

你可以做的NSLog,看到的JSONObject中存储什么信息? – yeesterbunny

回答

2

我觉得你使用了错误的服务--IT应该是... findNearbyPostalCodesJSON ....要使用JSON服务,据我可以从他们的网站告诉。这是他们的榜样网址:

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

+0

@yeestyerbunny,jsonObject为空,我也记录了长度,它是零,但我的网址得到了我正在寻找的。嗯...... – brianhevans

+0

里克,我先试了一个。同样的区别。顺便说一句,我有一些好消息给你...... – brianhevans

+0

@Ric,我只是试了一下JSON,而我得到了数据:) – brianhevans

相关问题