2013-05-10 41 views
13

要登记数据发送到服务器发送嵌套JSON,我使用JSON是以下形式:使用AFNetworking

这是怎么了发送。

NSURL * url = [[NSURL alloc] initWithString:registerUrlString]; 
      AFHTTPClient * httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 
      httpClient.parameterEncoding = AFJSONParameterEncoding; 
      [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; 
      NSDictionary * params = @{@"regData": @{ 
               @"City": self.cityField.text, 
               @"Country": self.countryField.text, 
               @"Email_Id": self.emailField.text, 
               @"MobileNumber": self.numberField.text, 
               @"UserName": self.userName.text, 
               } 
             }; 

      NSMutableURLRequest * request = [httpClient requestWithMethod:@"POST" path:registerUrlString parameters:params]; 
      AFHTTPRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
       NSLog(@"Success: %@", JSON); 

      } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
      NSLog(@"Error: %@", [error debugDescription]); 
      }]; 

      [operation start]; 

但不幸的是我收到此错误:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x94b3c30 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

+1

你的方法不是通用的。检查适当的方法[这里](http://stackoverflow.com/questions/14958883/ios-serialize-deserialize-complex-json-generically-from-nsobject-class)。更少的错误倾向和可维护性 – 2013-05-28 09:58:56

回答

32

您的要求是罚款。错误Error Domain=NSCocoaErrorDomain Code=3840正在返回,因为您的服务器响应无效的JSON对象。 NSLogoperation.responseString查看正在发回的内容。

+2

谢谢,mattt!我已经解决了这个问题。问题就像你提到的那样。我从服务器而不是json获取字符串。 – Homam 2013-05-24 04:27:23

+1

@mattt,我subclassed,'AFHTTPSessionManager'在哪里可以找到'operation.responseString'? – Hemang 2014-11-19 06:46:30

+0

@Hemang您是否发现任何与“错误域= NSCocoaErrorDomain代码= 3840”相关的解决方案? – Akhtar 2015-05-04 09:22:55

2

尝试使用此方法获得实际的错误

NSLog(@"Error: %@", [error debugDescription]); 
NSLog(@"Error: %@", [error localizedDescription]); 
+4

我得到此错误:错误域= NSCocoaErrorDomain代码= 3840“该操作无法完成。(可可错误3840.)”(JSON文本没有开始数组或对象和选项允许)UserInfo = 0x94b3c30 {NSDebugDescription = JSON文本没有以数组或对象开始,选项允许片段未设置。} – Homam 2013-05-10 07:05:07