问题:
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);
}];
这是送 recommended way 请求AFNetworking 2.0
GET
.我想要得到的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
特定键的值?
答案
默认情况下,
AFHTTPRequestOperationManager
responseSerializer
设置为一个
AFJSONResponseSerializer
实例,因此
responseObject
已经是你的已解析的JSON(你的情况,它会根据你所说的是一个
NSDictionary
).
然后,只是用它作为你会使用字典:
NSString *value = responseObject[@"someKey"];
响应对象已经是一本字典! AFNetworking做了处理,对你.
参考:http://www.freeshow.net.cn/questions/a8ddaf2cdccbdd6ccf59b1451dcbc0c8a62aec01a36275181e3b77845bdd7ccd/
Answer:
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"];
参考:http://stackoverflow.com/questions/19086660/afnetworking-2-0-use-responseobject-as-nsdictionary
本文介绍如何使用 AFNetworking 的 AFHTTPRequestOperationManager 发起 GET 请求并正确解析返回的 JSON 数据。默认情况下,AFHTTPRequestOperationManager 使用 AFJSONResponseSerializer 处理响应,使 responseObject 成为已解析的 JSON 对象。
1万+

被折叠的 条评论
为什么被折叠?



