将AFHTTPRequestOperation.responseString作为NSDictionary转换为NSString

时间:2015-07-22 20:10:38

标签: ios objective-c nsdictionary afnetworking

          if (operation.response.statusCode == 404) {
              NSDictionary *res = (NSDictionary *)operation.responseString;
              NSLog(@"res: %@ %@", res, res.class);

res: {".. a bunch of valid json that validates on json.lint.org"} __NSCFString

碰撞:

 <Error>: -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x16c21400
 <Error>: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x16c21400'
    *** First throw call stack:
    (0x26e46fef 0x350f8c8b 0x26e4c409 0x26e4a327 0x26d79e78 0x9b0bb 0x637e3 0x4de173 0x4de15f 0x4e1e45 0x26e0c609 0x26e0ad09 0x26d57201 0x26d57013 0x2e636201 0x2a4fba59 0x7f369 0x35684aaf)

2 个答案:

答案 0 :(得分:0)

转换并不意味着字符串会成为字典。这只是让编译器静音的一种方法。 responseString是一个字符串,因此应该这样对待。但是我记得应该有办法获得你想要的词典:

成功块有一个responseObject参数,很可能是NSData的一个实例。可以使用NSDictionary将其转换为NSJSONSerialization

NSDictionary* dictionary = [NSJSONSerialization jsonObjectWithData:responseObject options:kNilOptions error:nil];

答案 1 :(得分:0)

您的字典不在responseString中,但在responseObject中,如果您使用的是AFJSONRequest / ResponseSerializers。请参阅以下代码:

    - (void)makeAsyncRequest:(NSString *) urlString {
    // Send asynchronous request
    [appDelegate initiateNetworkActivityCounter];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:70 ];
    [request setHTTPMethod: @"GET" ];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];


    [manager GET:request.URL.absoluteString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self notifyOnFinishedLoading:(NSDictionary *) responseObject];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self notifyOnError];
    }];
}

使用notifyOnFinishedLoading的行显示如何将responseObject作为NSDictionary发送。您还必须小心,有时JSON会发回NSArray而不是NSDictionary,具体取决于您传入的JSON。