我正在尝试解析一个来自位于以下位置的api请求的json字符串:
http://www.physics.leidenuniv.nl/json/news.php
http://www.physics.leidenuniv.nl/json/news.php
但是,我无法解析这个json.
我收到以下错误:
字符串解析期间文件的意外结束
我已经找了几个小时,但是我找不到这个问题的答案.
我的代码段:
在我的viewDidLoad:
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.physics.leidenuniv.nl/json/news.PHP"]]; [[NSURLConnection alloc] initWithRequest:request delegate:self];
代表:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSMutableData *responseData = [[NSMutableData alloc] init]; [responseData appendData:data]; NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSError *e = nil; NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e]; }
任何人都知道这个问题的答案,所以我可以解析json数据?
解决方法
这样做:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // Append the new data to receivedData. // receivedData is an instance variable declared elsewhere. [responseData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSError *e = nil; NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e]; }