我有一个简单的 JSON 数组,它是从传递给第三方服务的邮政编码返回的。
尝试反序列化结果时出现未知错误,我不确定出了什么问题。
这是我的 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.");
}
}