AFNetworking返回_NSCFData对象而不是JSON

时间:2012-08-05 07:45:27

标签: afnetworking

我正在向AFHTTPClient的实例发送以下消息。我希望成功块被发送一个Foundation对象(字典),但调试器向我显示JSON是一个_NSCFData对象。 This question on SO声明我需要将Accept标头设置为'application / json'。好吧,我正在这样做,但AFNetworking仍然没有在响应体中解码JSON。如果我使用NSJSONSerialization自己解码json,我会得到一个我期望的NSDictionary。我做错了什么?

[client setDefaultHeader:@"Accept" value:@"application/json"];
[client postPath:@"/app/open_connection/"
  parameters:params
     success:^(AFHTTPRequestOperation *operation, id JSON) {
         NSLog(@"successful login! %@", [JSON valueForKeyPath:@"status"]);
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"error opening connection");
         NSAlert *alert = [NSAlert alertWithError:error];
         [alert runModal];
     }
];

注意:我正在使用Django在Python中编写服务器。响应的内容类型是'application / json'

2 个答案:

答案 0 :(得分:6)

当您使用AFHTTPClient和JSON API时,通常需要设置所有这三个设置:

httpClient.parameterEncoding = AFJSONParameterEncoding;
[httpClient setDefaultHeader:@"Accept" value:@"application/json"];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

现在,当您使用客户端发出请求时,它会知道将响应解析为JSON。

[httpClient postPath:@"/app/open_connection/"
          parameters:params
             success:^(AFHTTPRequestOperation *operation, id response) {
                 NSLog(@"JSON! %@", response);
             }
             failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             }];

这也是我发现的一个技巧。在NSError对象中,您可以解析它并检索错误消息(如果HTTP响应有JSON错误消息):

failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSDictionary *JSON =
    [NSJSONSerialization JSONObjectWithData: [error.localizedRecoverySuggestion dataUsingEncoding:NSUTF8StringEncoding]
                                    options: NSJSONReadingMutableContainers
                                      error:nil];
           failureCallback(JSON[@"message"]);
}

答案 1 :(得分:3)

试试这个...我认为您的客户端设置可能有问题。

NSMutableURLRequest *request = [client requestWithMethod:@"POST" path:@"/app/open_connection/" parameters:params];

AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request 
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"successful login! %@", [JSON valueForKeyPath:@"status"]);
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"error opening connection");
        NSAlert *alert = [NSAlert alertWithError:error];
        [alert runModal];
}];
[operation start];