如何使用 JSON 格式解析通过 AFNetworking 1.0 获得的响应

How to parse a response obtained with AFNetworking 1.0 using JSON format

我遇到了 AFNetworking 的问题。

目前我可以使用 NSDictionaryJSON 格式 [AFJSONParameterEncoding] 向服务器发送 POST 请求并正确回复,问题是服务器也使用 JSON 格式的响应进行回复,我可以使用以下方法将响应转换为 NSString

[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// responseObject is the server response

问题是除了之前发布的代码中的 NSString 之外,我无法将响应转换为任何其他格式。这怎么可能?我想将响应转换为 JSON 格式,以便我可以读取精确值,即与键 "isInformative"

关联的值

到目前为止,这是我的代码:

NSDictionary *requestBody = [NSDictionary dictionaryWithObjectsAndKeys:
                                     @"value1", @"key1",
                                     @"value2", @"key2",
                                     nil];

NSDictionary *requestHead = @{
                              @"RequestHead": requestBody
                             };

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://XXX.XXX.XXX.XXX:XXXX"]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                        path:@"/public-mobile-sdk/"
                                                  parameters:requestHead];

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *requestOperation, id responseObject) {
    // Here I can convert the responseObject to NSSTring correctly
    NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);

    } failure:^(AFHTTPRequestOperation *requestOperation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[requestOperation start];

注意 - 我无法更新捆绑在 Xcode 项目中的 AFNetworking 版本,因为它不是我自己的,所以遗憾的是我必须坚持使用版本 1.X

这解决了我的问题:

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:jailbreakRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *requestOperation, id responseObject) {
    //Place this line of code below to create a NSDictionary from the async server response
    NSDictionary *jsonList = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
    } failure:^(AFHTTPRequestOperation *requestOperation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[requestOperation start];

谢谢你:-)