ios AFNetworking 2.0 - 使用 responseObject 作为 NSDictionary

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19086660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:51:48  来源:igfitidea点击:

AFNetworking 2.0 - use responseObject as NSDictionary

iosiphoneobjective-cnsdictionaryafnetworking-2

提问by Brian

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

this is the recommended wayto send GETrequest in AFNetworking 2.0. I want to get the value of a specific key in the json, so I want to use responseObjectas NSDictionary. this is what I was trying:

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

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

it didn't work:

它没有用:

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

how can I get the value of a specific key in responseObject?

如何获取特定键的值responseObject

回答by Marcelo Fabri

By default, AFHTTPRequestOperationManagersets responseSerializerto an AFJSONResponseSerializerinstance, so responseObjectalready is your parsed JSON (in your case, it'll be an NSDictionaryaccording to what you said).

默认情况下,AFHTTPRequestOperationManager设置responseSerializer为一个AFJSONResponseSerializer实例,因此responseObject已经是您解析的 JSON(在您的情况下,它将NSDictionary根据您所说的进行)。

Then, just use it as you'd use a dictionary:

然后,就像使用字典一样使用它:

NSString *value = responseObject[@"someKey"];

回答by vikingosegundo

The response object is already a dictionary! AFNetworking did handle that for you.

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