使用AFNetworking发送嵌套JSON

Hom*_*mam 13 iphone json nsdictionary ios afnetworking

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

{"regData": {
 "City":"Some City",
 "Country":"Some Country",
 "Email_Id":"abc@gmail.com",
 "MobileNumber":"+00xxxxxxxxxx",
 "UserName":"Name Of user"
 }
}
Run Code Online (Sandbox Code Playgroud)

这是我发送的方式.

 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];
Run Code Online (Sandbox Code Playgroud)

但不幸的是我收到了这个错误:

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

mat*_*ttt 32

你的要求没问题.Error Domain=NSCocoaErrorDomain Code=3840由于您的服务器使用无效的JSON对象进行响应,因此返回错误.NSLog operation.responseString看看被送回去了什么.

  • 谢谢,马特!我已经解决了这个问题.问题就像你提到的那样.我从服务器而不是json获取字符串. (2认同)