简体   繁体   中英

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?

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 .

self.responseSerializer = [AFHTTPResponseSerializer serializer];

The default value is AFJSONResponseSerializer . If you don't want it to convert the JSON for you, change the response serializer.

You can access the “data” object directly from AFNetworking by using the “AFNetworkingOperationFailingURLResponseDataErrorKey” key so there is no need for subclassing the 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.

I added the following line in the AFURLSessionManager.m file.

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

in this NSURLSessionTaskDelegate delegate method

- (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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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