【问题标题】:JSON parsing with AFNetworking使用 AFNetworking 解析 JSON
【发布时间】:2013-06-24 02:03:16
【问题描述】:

我正在尝试从 Web api 捕获 JSON 请求。当我从服务器获得 JSON 格式的响应时,我以 NSData 格式而不是 NSDictionnary 接收它。我从本教程http://www.raywenderlich.com/30445/afnetworking-crash-course#(RESTful 类段落)中得到启发,以便通过 AFJSONRequestOperation 更改我的客户端的注册操作类来进行免费的 JSON 解析。但是,它不起作用,我仍然得到 NSData 格式的响应。

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

*** 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]];
}];

【问题讨论】:

  • 你真的查过responseObject的类吗?
  • 完整的错误信息会很有帮助...
  • 抱歉,添加了完整的错误消息。至于responseObject的类,我用isKindOfClass方法查了一下,其实是一个NSData。
  • self.jsonResponse 的第二个作业上面的评论看来,你已经明白了。您需要使用NSJSONSerialization API 将NSData 转换为字典。

标签: ios json afnetworking


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您错过了对 setDefaultHeader:value: 的调用以将 Accept 标头设置为 application/json。没有这个,JSON 操作类将不会被使用,这意味着要退回到AFHTTPRequestOperation,它使用responseData 作为它的responseObject

    【讨论】:

    • 正确!头球已定,一切顺利,来自马特汤普森!感谢 AFNetworking 库,祝您在 Heroku 项目中好运。
    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多