为什么不直接使用 NSJSONSerialization 方法 JSONObjectWithData:options:error: 它对我来说很好用。
NSString *url = @"http://qdreams.com/laura/index.php?request=EventWeekListings&year=2012&month=10&day=22";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",arr);
编辑后:我今天早上再次运行代码,和你一样我得到了空值。dataWithContentsOfURL 的问题。是您无法控制,也无法知道如果出现问题会发生什么。所以,我用下面的代码重新测试:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[self loadData];
}
-(void) loadData {
NSLog(@"loadData...");
self.receivedData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:@"http://qdreams.com/laura/index.php?request=EventWeekListings&year=2012&month=10&day=22"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10.0];
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"didReceiveResponse...");
[self.receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"didReceiveData...");
NSLog(@"Succeeded! Received %ld bytes of data",[data length]);
[self.receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"didFailWithError...");
NSLog(@"Connection failed! Error - %@ %@",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
//lblError.text = [NSString stringWithFormat:@"Connection failed! Error - %@",[error localizedDescription]];
self.receivedData = nil;
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading...");
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:self.receivedData options:kNilOptions error:&error];
if (error) {
NSLog(@"%@",error.localizedDescription);
NSLog(@"%@",[[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]);
}else{
NSLog(@"Finished...Download/Parsing successful");
if ([result isKindOfClass:[NSArray class]])
NSLog(@"%@",result);
}
}
出现错误,error.localizesDescription 的日志为:“数据已损坏,无法读取”。因此,从服务器返回的内容似乎有问题,导致 JSON 解析器无法正常工作。我还打印了字符串以及错误消息。也许您可以仔细查看并尝试找出数据出了什么问题。