2013-06-26 125 views
2

我想从网页api赶上JSON请求。当我从服务器获得JSON格式的响应时,我会以NSData格式接收它,而不是在NSDictionnary中。我从本教程http://www.raywenderlich.com/30445/afnetworking-crash-course#(一个RESTful类的段落)中启发了我自己,以便通过AFJSONRequestOperation更改我的客户端的注册操作类来实现免费的JSON解析。但是,它不起作用,我仍然以NSData格式获得响应。JSON解析与AFNetworking

编辑:以下是完整的错误消息:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData objectForKey:]: unrecognized selector sent to instance 0x753aa00' 

这里是服务器的响应:

{"uid":"98545931","token":"98545931:176:ec0b862ba57fef88394950dd0cc41491"} 

是否有人有一个想法,为什么它不能被自动解析?

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseurl]; 
//Here, we tell the AFHTTPClient that the server is responding to us in JSON format. 
[client registerHTTPOperationClass:[AFJSONRequestOperation class]]; 

//Creating the dictionary containing the post parameters. 
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:username, @"username", password, @"password", nil]; 


//AUTHENTIFICATION. Retrieving token and uid by POST method. 
[client postPath:@"/auth" parameters:params 
     success:^(AFHTTPRequestOperation *operation, id responseObject) 
{ 
    NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 
    NSLog(@"Response: %@", text); 
    [responseField setText:text]; 
    self.jsonResponse = responseObject; 

    //The NSJSONSerialization method to transform the NSData responseObject into a dictionnary does work 
    self.jsonResponse = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil]; 

    //This NSLog makes the app crash with an unrecognized selector sent error 
    NSLog(@"User ID: %@",[jsonResponse objectForKey:@"uid"]); 
} 
     failure:^(AFHTTPRequestOperation *operation, NSError *error) 
{ 
      NSLog(@"%@", [error localizedDescription]); 
      [responseField setText:[error localizedDescription]]; 
}]; 
+0

你真的检查过'responseObject'类吗? – Wain

+0

完整的错误信息会有帮助... –

+0

对不起,添加完整的错误信息。至于responseObject的类,我使用isKindOfClass方法进行了检查,它实际上是一个NSData。 –

回答

6

你缺少setDefaultHeader:value:打电话给Accept头设置为application/json。如果不这样做,将不会使用JSON操作类,这意味着回退到AFHTTPRequestOperation,其使用responseData作为其responseObject

+0

正确!标题已设置,并且所有内容都顺利运行,并且来自Matt Thompson!感谢图书馆AFNetworking,并感谢正在进行的Heroku项目。 –

+2

如果这解决了您的问题,请接受答案! – fatuhoku

1

只需将默认的标头接受设置为application/json的值与setDefaultHeader:value:为了告诉AFHTTPRequestOperation它实际上是我们在回调中获得的JSON。