AFNetworking 2.0 - 使用responseObject作为NSDictionary

Bri*_*ian 18 iphone objective-c nsdictionary ios 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);
}];
Run Code Online (Sandbox Code Playgroud)

这是在AFNetworking 2.0中发送请求的推荐方法GET.我想获得json中特定键的值,所以我想用responseObjectas NSDictionary.这就是我的尝试:

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

它不起作用:

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary bytes]: unrecognized selector sent to instance 0xa048120'
Run Code Online (Sandbox Code Playgroud)

如何获取特定键的值responseObject

Mar*_*bri 31

默认情况下,AFHTTPRequestOperationManager设置responseSerializerAFJSONResponseSerializer实例,因此responseObject已经解析的JSON(在您的情况下,它将NSDictionary根据您的说法而定).

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

NSString *value = responseObject[@"someKey"];
Run Code Online (Sandbox Code Playgroud)


Vik*_*ica 5

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