我尝试了几个将 responseSerializer 设置为 JSON 的选项,但我无法将 responseObject 转换为 NSDictionary 。问题是我得到的响应是 NSData
NSString *baseURLString = @"Your URL?";
NSString *str = @"adult=false&gender=male";
NSString *url = [NSString stringWithFormat"%@%@",baseURLString,str];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
// do whatever you'd like here; for example, if you want to convert
// it to a string and log it, you might do something like:
NSLog(@"responseObject %@",responseObject);
NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseObject
options:NSJSONReadingMutableContainers
error:&error];
NSLog(@"json %@",json);
if (error) {
NSLog(@"%@",[error description]);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
这个 NSLog(@"%@",[error description]); 给出的错误如下:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed.
(Cocoa error 3840.)" (Garbage at end.)
UserInfo=0xa7c5440 {NSDebugDescription=Garbage at end.}
Best Answer-推荐答案 strong>
您的 JSON 最后返回垃圾。
您应该修复您的 web 服务,使其不在 JSON 末尾嵌入时间戳和语言。如果您无法更改您的网络服务,请使用以下方法从您的 json 中删除尾随垃圾,然后再次使用 NSJSONSerialization 解析它。
NSRange range = [jsonString rangeOfString"}" options:NSBackwardsSearch];
jsonString = [jsonString substringToIndex:range.location + 1];
然后将这个清理后的 jsonString 解析为 NSDictionary :
NSData *newJSONData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:newJSONData
options:NSJSONReadingMutableContainers
error:&error];
NSLog(@"json %@",json);
它应该可以正常工作。
关于ios - AFNetworking GET 请求 - 无法将 responseObject 转换为 NSDictionary,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/22370420/
|