我在 AFNetworking
方面遇到问题。
目前,我可以使用 NSDictionary
以 JSON
格式 [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];
还是谢谢 :-)
关于ios - 如何使用 JSON 格式解析通过 AFNetworking 1.0 获得的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28917719/