【发布时间】:2013-01-05 08:41:09
【问题描述】:
在提交我的 AFNetworking 请求后,我不断收到以下错误消息:2013-01-22 01:44:43.091 Section3App2[16625:6703] -[__NSCFArray length]: unrecognized selector sent to instance 0x23a48780。请求背后的想法是,我们通过 POST 向带有 JSON 请求正文的 REST API 发送一个 post 请求。我整天都在摆弄这个,似乎无法弄清楚是什么导致了问题。
代码
NSString *string = @"[{\"code\":\"105N14560\"}]"; NSString * jsonString = 字符串; NSData * 数据 = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError * 错误 = 零; id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; [请求 setHTTPBody:json]; // [请求 setValue:[NSString stringWithFormat:@"%d", string.length] forHTTPHeaderField:@"Content-Length"]; NSLog(@"请求正文:%@", request.HTTPBody); // NSLog(@"json: %@",json); // 如果 (!json) { // // 处理错误 // NSLog(@"失败"); // } AFJSONRequestOperation *operation2 = [AFJSONRequestOperation JSONRequestOperationWithRequest:请求成功:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { NSLog(@"JSON: %@", JSON); } 失败:无]; [操作2开始];该代码成功地创建了请求正文,但是当它尝试运行该块时,它会抛出错误,我完全被难住了。我们将不胜感激所有帮助。
【问题讨论】:
-
请注意,您将
json作为参数传递给setHTTPBody:。根据文档,这应该是一个NSData对象,但您已经通过反序列化您构造的 JSON 字符串向它传递了一个NSArray。只需将data作为参数传递,您无需在发布 JSON 之前对其进行反序列化。
标签: objective-c json ios6 afnetworking