简体   繁体   English

如何从AFnetworking 2.0操作/ NSURLSessioNDataTask获取原始JSON响应?

[英]how to get raw JSON response from AFnetworking 2.0 operation / NSURLSessioNDataTask?

This is my code.. its a very simple operation 这是我的代码..它是一个非常简单的操作

[self GET:operationName parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
          NSLog(@"%@", responseObject);
          //do something upon success
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
         //do something to handle error
    }];

My question is, I need to see what the exact raw json response is.. when I NSLog the responseObject, it's not the same JSON output that I would get from a standalone HTTP client _ I guess its because it's been through the serializer? 我的问题是,我需要看看确切的原始json响应是什么..当我NSLog的responseObject时,它与我从独立的HTTP客户端得到的JSON输出不一样_我猜它是因为它是通过序列化器?

If you don't want it to do the NSJSONSerialization conversion to NSArray / NSDictionary , but rather want the raw NSData , you should set the responseSerializer of the AFURLSessionManager to a AFHTTPResponseSerializer . 如果您不希望它将NSJSONSerialization转换为NSArray / NSDictionary ,而是希望原始NSData ,则应将AFURLSessionManagerresponseSerializer设置为AFHTTPResponseSerializer

self.responseSerializer = [AFHTTPResponseSerializer serializer];

The default value is AFJSONResponseSerializer . 默认值为AFJSONResponseSerializer If you don't want it to convert the JSON for you, change the response serializer. 如果您不希望它为您转换JSON,请更改响应序列化程序。

You can access the “data” object directly from AFNetworking by using the “AFNetworkingOperationFailingURLResponseDataErrorKey” key so there is no need for subclassing the AFJSONResponseSerializer. 您可以使用“AFNetworkingOperationFailingURLResponseDataErrorKey”键直接从AFNetworking访问“数据”对象,因此不需要对AFJSONResponseSerializer进行子类化。 You can the serialize the data into a readable dictionary. 您可以将数据序列化为可读字典。 Here is some sample code : 以下是一些示例代码:

 NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
 NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil];

It's hard to hook the raw response from AF using their API, and their logger even on Debug level deserializes the JSON before outputting to the console. 使用他们的API挂钩AF的原始响应很困难,甚至在调试级别上他们的记录器也会在输出到控制台之前反序列化JSON。

I added the following line in the AFURLSessionManager.m file. 我在AFURLSessionManager.m文件中添加了以下行。

NSLog(@"Response String: %@", [[NSString alloc] initWithData:[NSData dataWithData:self.mutableData] encoding:NSUTF8StringEncoding]);

in this NSURLSessionTaskDelegate delegate method 在这个NSURLSessionTaskDelegate委托方法中

- (void)URLSession:(__unused NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error

and here it is in context (for a successful response, without error) 在这里它是在上下文中(为了成功响应,没有错误)

{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
__strong AFURLSessionManager *manager = self.manager;

__block id responseObject = nil;

__block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;

if (self.downloadFileURL) {
    userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
} else if (self.mutableData) {
    userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = [NSData dataWithData:self.mutableData];
}

if (error) {
    userInfo[AFNetworkingTaskDidCompleteErrorKey] = error;

    dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
        if (self.completionHandler) {
            self.completionHandler(task.response, responseObject, error);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
        });
    });
} else {
    dispatch_async(url_session_manager_processing_queue(), ^{
        NSError *serializationError = nil;
        NSLog(@"Response String: %@", [[NSString alloc] initWithData:[NSData dataWithData:self.mutableData] encoding:NSUTF8StringEncoding]);
        responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:[NSData dataWithData:self.mutableData] error:&serializationError];

        if (self.downloadFileURL) {
            responseObject = self.downloadFileURL;
        }

        if (responseObject) {
            userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
        }

        if (serializationError) {
            userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
        }

        dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
            if (self.completionHandler) {
                self.completionHandler(task.response, responseObject, serializationError);
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
            });
        });
    });
}
#pragma clang diagnostic pop
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM