Objective-C解析来自URL请求的JSON

10

我正试图解析从以下位置的API请求的json字符串: http://www.physics.leidenuniv.nl/json/news.php

但是,我在解析此JSON时遇到了问题。 我收到以下错误消息: Unexpected end of file during string parse

我已经搜索了几个小时,但无法找到解决此问题的答案。

我的代码片段:

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


3
didReceiveData被调用并不意味着所有数据都已经接收完毕,可能还有更多的数据需要到来。 - Hot Licks
实际上,didReceiveData方法将会被多次调用,并传递一部分数据。你需要实例化一个NSData对象,并将这些数据块依次粘贴到其中。 - shinyuX
尝试使用 AFNetworking - Khanh Nguyen
7个回答

34

我建议这样做:

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);

9

按照以下方式进行:

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

}

1
//call this method
-(void)syncWebByGETMethod
{
      [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    NSString *urlString = [NSString stringWithFormat:@"http://www.yoursite.com"];
    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
   [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]                          completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
        {
         if (data)
         {
             id myJSON;
             @try {
                 myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
             }
             @catch (NSException *exception) {
             }
             @finally {
             }
             jsonArray = (NSArray *)myJSON;

             NSLog(@"mmm %@",jsonArray);
         }
     }];
}

1
简单的方法将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); 

你可以尝试这个,非常简单。

0

VolunteerMatch API Objective C

我正在使用一种常见的方法来调用 AFNetworking 的 Web 服务。用途如下:

调用 Web 服务:

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类在整个项目中使用这些通用方法。 另外添加 // 定义错误代码如下...

定义kDefaultErrorCode为12345

- (void)requestWithUrlString:(NSString *)stUrl parmeters:(NSDictionary *)parameters success:(void (^)(NSDictionary *response))success failure:(void (^)(NSError *error))failure {

[self requestWithUrl:stUrl parmeters:parameters success:^(NSDictionary *response) {
    if([[response objectForKey:@"success"] boolValue]) {
        if(success) {
            success(response);
            
        }
    }
    else {
        NSError *error = [NSError errorWithDomain:@"Error" code:kDefaultErrorCode userInfo:@{NSLocalizedDescriptionKey:[response objectForKey:@"message"]}];
        if(failure) {
            failure(error);
        }
    }
} failure:^(NSError *error) {
    if(failure) {
        failure(error);
    }
}];}

并且 // 在下面的方法中设置头信息(如果需要的话,否则请删除)

- (void)requestWithUrl:(NSString *)stUrl parmeters:(NSDictionary *)parameters success:(void (^)(NSDictionary *response))success failure:(void (^)(NSError *))failure {

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];


[manager.requestSerializer setValue:@"WWSE profile=\"UsernameToken\"" forHTTPHeaderField:@"Authorization"];



[manager GET:stUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    if([responseObject isKindOfClass:[NSDictionary class]]) {
        if(success) {
            success(responseObject);
        }
    }
    else {
        NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if(success) {
            success(response);
        }
    }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
    if(failure) {
        failure(error);
    }
}];}

如有任何问题或需要更多详细信息请访问..AFNetworking


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

0

一种解决方法是使用NSURLConnection sendSynchronousRequest:returningResponse:error:(docs)。在完成处理程序中,您将拥有所有响应数据,而不仅仅是您在委托的connection:didReceiveData:方法中收到的部分数据。

如果您想继续使用代理,您需要遵循Apple docs中的建议:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接