使用AFNetworking进行JSON解析

Ale*_* S. 2 json ios afnetworking

我试图从Web api捕获JSON请求.当我从服务器JSON格式的响应,我接受它在NSData的格式,而不是在NSDictionnary.我启发自己从本教程http://www.raywenderlich.com/30445/afnetworking-crash-course#为了通过AFJSONRequestOperation变更登记操作类我的客户有自由JSON解析(A类REST风格的段落).但是,它不工作,我仍然得到的NSData格式的响应.

编辑:这是完整的错误消息:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData objectForKey:]: unrecognized selector sent to instance 0x753aa00'
Run Code Online (Sandbox Code Playgroud)

这是服务器的响应:

{"uid":"98545931","token":"98545931:176:ec0b862ba57fef88394950dd0cc41491"}
Run Code Online (Sandbox Code Playgroud)

有人知道为什么它不能自动解析吗?

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]];
}];
Run Code Online (Sandbox Code Playgroud)

mat*_*ttt 6

您错过了setDefaultHeader:value:Accept标头设置为的调用application/json.如果没有这个,将不会使用JSON操作类,这意味着重新使用AFHTTPRequestOperation,它使用responseDataas作为其responseObject.

  • 如果这解决了您的问题,请接受答案! (2认同)