使用AFNetworking发送嵌套JSON

时间:2013-05-10 06:29:44

标签: iphone ios json nsdictionary afnetworking

要将注册数据发送到服务器,我使用JSON的形式如下:

{"regData": {
 "City":"Some City",
 "Country":"Some Country",
 "Email_Id":"abc@gmail.com",
 "MobileNumber":"+00xxxxxxxxxx",
 "UserName":"Name Of user"
 }
}

以下是发送方式。

 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.}

2 个答案:

答案 0 :(得分:32)

您的要求没问题。正在返回错误Error Domain=NSCocoaErrorDomain Code=3840,因为您的服务器正在使用无效的JSON对象进行响应。 NSLog operation.responseString查看发回的内容。

答案 1 :(得分:2)

尝试此操作以获取实际错误

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