本文介绍了AFNetworking 2.0 - 使用responseObject作为NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 请求。我想获取json中特定键的值,所以我想使用 responseObject 作为 NSDictionary 。这就是我的尝试:

this is the recommended way to send GET request in AFNetworking 2.0. I want to get the value of a specific key in the json, so I want to use responseObject as NSDictionary. this is what I was trying:

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 中获取特定键的值?

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

推荐答案

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

By default, AFHTTPRequestOperationManager sets responseSerializer to an AFJSONResponseSerializer instance, so responseObject already is your parsed JSON (in your case, it'll be an NSDictionary according to what you said).

然后,只需使用它,因为你使用字典:

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

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

这篇关于AFNetworking 2.0 - 使用responseObject作为NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 20:47