【问题标题】:How to parse a response obtained with AFNetworking 1.0 using JSON format如何使用 JSON 格式解析通过 AFNetworking 1.0 获得的响应
【发布时间】:2015-03-07 17:22:10
【问题描述】:

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 版本

【问题讨论】:

标签: ios objective-c json post afnetworking


【解决方案1】:

这解决了我的问题:

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

还是谢谢 :-)

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多