0

我知道我的请求格式正确,但我从 Web 服务获得的响应不是 NSDictionary。

  1. 为什么它不是 NSDictionary?
  2. 如何判断“responseObject”是什么类型的对象?

    AFHTTPRequestOperation *operation = [[AFParseAPIClient sharedClient]  HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSLog(@"Response for %@: %@", className, responseObject);
            [self writeJSONResponse:responseObject toDiskForClassWithName:className];
        }else{
            //NSLog(@"Response NOT NSDictionary: %@", [responseObject class]);
            NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"str: %@", str);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Request for class %@ failed with error: %@", className, error);
    }];
    

这是我得到的:

//Response NOT NSDictionary: <7b227265 73756c74 73223a5b 7b22636f ...>

编辑:这是我回来的:

str: {"results":[{"desc":"My description.","device_iPad":true,"device_iPhone":true,"createdAt":"2012-09-05T18:36:11.431Z","updatedAt":"2012-09-05T22:00:52.199Z"}]}
4

4 回答 4

4

只需在创建操作后添加这行代码

operation.responseSerializer = [AFJSONResponseSerializer 序列化器];

于 2015-04-16T15:25:41.890 回答
2

我遇到了同样的问题,但使用 AFHTTPClient 的子类执行请求。我得到的是 __NSCFData 而不是 __NSCFDictionary。我用这个解决了它:

[self setDefaultHeader:@"Accept" value:@"application/json"];

self 是我的 AFHTTPClient 子类。

于 2013-08-24T03:35:50.537 回答
1

这对你有用吗?它来自 AFNetworking github项目

NSURL *url = [NSURL URLWithString:@"https://gowalla.com/users/mattt.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperationJSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"Name: %@ %@", [JSON valueForKeyPath:@"first_name"], [JSON valueForKeyPath:@"last_name"]);
} failure:nil];

[operation start];

试一试,很简单。*如果它仍然是一个数组做[[JSON objectAtIndex:0] objectForKey@"desc /*(or whatever)*/"]

于 2012-09-05T22:22:22.033 回答
0

使用 AFJSONRequestOperation 和 AFNetworking 返回 JSON 响应。使用 AFHTTPRequestOperation 返回 NSData ,您可以将其转换(转换)为 NSDictionary 并使用以下命令进行打印:

NSLog(@"响应:%@", [[NSString alloc] initWithData:(NSData *)json encoding:NSUTF8StringEncoding]);

我的建议是只使用 AFJSONRequestOperation!

于 2014-01-03T05:03:38.683 回答