2012-10-30 37 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

相關問題