ios – 目标c从url请求解析json

前端之家收集整理的这篇文章主要介绍了ios – 目标c从url请求解析json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试解析一个来自位于以下位置的api请求的json字符串:
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];

}

猜你在找的iOS相关文章