Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 目标c从url请求解析json_Ios_Objective C_Json - Fatal编程技术网

Ios 目标c从url请求解析json

Ios 目标c从url请求解析json,ios,objective-c,json,Ios,Objective C,Json,我正在尝试解析从位于以下位置的api请求的json字符串: 但是,我在解析这个json时遇到了问题。 我得到以下错误: 字符串解析期间文件意外结束 我找了好几个小时了,但我找不到这个问题的答案 我的代码片段: 在我的视图中: NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.physics.leidenuniv.nl/j

我正在尝试解析从位于以下位置的api请求的json字符串:

但是,我在解析这个json时遇到了问题。 我得到以下错误:
字符串解析期间文件意外结束

我找了好几个小时了,但我找不到这个问题的答案

我的代码片段:

在我的视图中:

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数据了?

一个解决方案是使用
NSURLConnection sendSynchronousRequest:returningResponse:error:
()。在完成处理程序中,您将拥有所有响应数据,而不仅仅是在委托的
连接:didReceiveData:
方法中获得的部分数据

如果您想继续使用该委托,您需要遵循以下建议:

委托应该连接每个数据对象的内容 交付以构建URL加载的完整数据

这样做:

- (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];

}
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.physics.leidenuniv.nl/json/news.php"]];

__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                           json = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:0
                                                                    error:nil];
                           NSLog(@"Async JSON: %@", 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];

}
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.physics.leidenuniv.nl/json/news.php"]];

__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                           json = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:0
                                                                    error:nil];
                           NSLog(@"Async JSON: %@", json);
                       }];
或者,如果出于任何原因(不推荐)您希望运行同步请求,您可以执行以下操作:

NSData *theData = [NSURLConnection sendSynchronousRequest:request
                      returningResponse:nil
                                  error:nil];

NSDictionary *newJSON = [NSJSONSerialization JSONObjectWithData:theData
                                                        options:0
                                                          error:nil];

NSLog(@"Sync JSON: %@", newJSON);

我使用一种常见的方法来调用AFWS。 用途:

呼叫WS:

NSDictionary* param = @{
                        @"action":@"helloWorld",
                        @"query":@"{\"name\":\"john\"}"
                        };

[self requestWithUrlString:@"URL" parmeters:paramDictionary success:^(NSDictionary *response) {
    //code For Success
} failure:^(NSError *error) {
   // code for WS Responce failure
}];
添加两种方法: 这两种方法是通用的,您可以使用NSObject类在整个项目中使用这些通用方法。 还加 //定义错误代码,如

定义KDEFaultErrorCode12345 及 //在下面的方法中设置标题(如果需要,请删除)


对于任何问题和更详细的信息

在字典中存储json url数据的简单方法

 NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://query.yahooapis.com/v1/public/yql?q=select+%2A+from+weather.forecast+where+woeid%3D1100661&format=json"]];
    NSError *error=nil;
    id response=[NSJSONSerialization JSONObjectWithData:data options:
                 NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];

    if (error) {
        NSLog(@"%@",[error localizedDescription]);
    } else {
        _query = [response objectForKey:@"query"];
        NSLog(@"%@",_query); 

您可以很容易地尝试这一点。

didReceiveData
被调用并不意味着所有数据都已被接收——可能还有更多数据要接收。事实上,didReceiveData方法将使用您的总数据块多次被调用。您必须实例化一个NSData并将块一个接一个地粘贴到其中。请尝试
-(void)getWebServic{
NSURL *url = [NSURL URLWithString:@"----URL----"];

// 2
NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession]
                                      dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
    NSDictionary *jsonObject=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    [self loadDataFromDictionary:(NSArray*)jsonObject];
    NSLog(@"data: %@",jsonObject);

}];

// 3
[downloadTask resume]; }
 NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://query.yahooapis.com/v1/public/yql?q=select+%2A+from+weather.forecast+where+woeid%3D1100661&format=json"]];
    NSError *error=nil;
    id response=[NSJSONSerialization JSONObjectWithData:data options:
                 NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];

    if (error) {
        NSLog(@"%@",[error localizedDescription]);
    } else {
        _query = [response objectForKey:@"query"];
        NSLog(@"%@",_query);