Ios 基于afp网络的JSON解析

Ios 基于afp网络的JSON解析,ios,json,afnetworking,Ios,Json,Afnetworking,我试图从web api捕获JSON请求。当我从服务器获得JSON格式的响应时,我将以NSData格式而不是NSDictionnary格式接收响应。我从本教程(RESTful类段落)中得到启发,通过AFJSONRequestOperation更改客户机的注册操作类,从而实现免费的JSON解析。但是,它不起作用,我仍然得到NSData格式的响应 {"uid":"98545931","token":"98545931:176:ec0b862ba57fef88394950dd0cc41491"} 编辑

我试图从web api捕获JSON请求。当我从服务器获得JSON格式的响应时,我将以NSData格式而不是NSDictionnary格式接收响应。我从本教程(RESTful类段落)中得到启发,通过AFJSONRequestOperation更改客户机的注册操作类,从而实现免费的JSON解析。但是,它不起作用,我仍然得到NSData格式的响应

{"uid":"98545931","token":"98545931:176:ec0b862ba57fef88394950dd0cc41491"}
编辑:以下是完整的错误消息:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData objectForKey:]: unrecognized selector sent to instance 0x753aa00'
{"uid":"98545931","token":"98545931:176:ec0b862ba57fef88394950dd0cc41491"}
以下是服务器的响应:

{"uid":"98545931","token":"98545931:176:ec0b862ba57fef88394950dd0cc41491"}
有人知道为什么不能自动解析吗

{"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]];
}];

您缺少对
setDefaultHeader:value:
的调用,无法将
Accept
头设置为
application/json
。没有这个,JSON操作类就不会被使用,这意味着回到
AFHTTPRequestOperation
,它使用
responseData
作为其
responseObject

只需使用
setDefaultHeader:value:
将默认头Accept设置为
application/json
值,以便告诉AFHTTPRequestOperation我们在回调中得到的实际上是json。

您确实检查了
responseObject
?完整的错误消息会很有帮助…抱歉,添加了完整的错误消息。至于responseObject的类,我用isKindOfClass方法检查了一下,它实际上是一个NSData。从上面的注释来看,
self.jsonResponse
的第二个赋值,听起来你已经解决了这个问题。您需要使用
NSJSONSerialization
API将
NSData
转换为字典。正确!头球已经设置好,一切都很顺利,马特·汤普森!感谢您的图书馆,祝您在Heroku项目中好运。
{"uid":"98545931","token":"98545931:176:ec0b862ba57fef88394950dd0cc41491"}