AFNetworking 2.0 - 使用responseObject作为NSDictionary

时间:2013-09-30 04:55:39

标签: ios iphone objective-c nsdictionary afnetworking-2

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

这是AFNetworking 2.0中发送GET recommended way请求的{{3}}。我想获取json中特定键的值,因此我想将responseObject用作NSDictionary。这就是我的尝试:

NSError *jsonError = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:kNilOptions error:&jsonError];

它不起作用:

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary bytes]: unrecognized selector sent to instance 0xa048120'

如何在responseObject中获取特定密钥的值?

2 个答案:

答案 0 :(得分:31)

默认情况下,AFHTTPRequestOperationManagerresponseSerializer设置为AFJSONResponseSerializer个实例,因此responseObject已经是您解析的JSON(在您的情况下,它将是{{1}根据你说的话。)

然后,只需在使用字典时使用它:

NSDictionary

答案 1 :(得分:5)

响应对象已经是字典了! AFNetworking确实为你处理了这个问题。