我可以在 AFNetworking 中使用 post 方法发送整个 JSON 对象吗

Can i send an entire JSON object using post method in AFNetworking

是否可以使用 AFNetworking AFHTTPRequestOperationManager 方法 post 将 JSON 对象发送到 Web 服务 (RESTful)?我知道我们可以通过字典发送键值对,并且可以通过 POST 请求将其序列化为 JSON 但这关于更复杂的对象如下

{
  "User":{ "name":"blah", "id":"blah blah" }
  "department":"something" 
}

我尝试的代码是这样的

 NewUser *user = [NewUser sharedNewUser];

     NSDictionary *params = @ {@"FirstName" :user.strFname, @"LastName" :user.strLname,@"Email":user.strEmail,@"PhoneNumber":user.strNum,@"Password":user.strPwd,@"Token":@""};

    NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc] init];
    [jsonDic setValue:params forKey:@"Client"];

    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"URL"]];


    [client postPath:@"chauffr_services/servicestack/RegisterClient?format=json" parameters:jsonDic
             success:^(AFHTTPRequestOperation *operation, id responseObject) {
                 NSLog(@"%@",responseObject);
                 NSDictionary *json = responseObject;


             } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

             }];

您可以使用此自定义方法实现此目的:

- (NSString *)jsonStringFromID:(id)object {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:(NSJSONWritingOptions)(0) error:&error];

if (!jsonData) {
    NSLog(@"Json Print: error: %@", error.localizedDescription);
    return @"{}";
}
else {
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

}

通过将您的 json 对象传递给它来调用此方法。 享受吧!!!

已编辑: 尝试将请求序列化程序添加为 json 类型。也许它适合你..

[[AFHTTPRequestOperationManager manager] setRequestSerializer:[AFJSONRequestSerializer serializer]];
[[[AFHTTPRequestOperationManager manager] requestSerializer] setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

我试图将对象发送到服务,但 jSON 没有到达 RESTful 服务,我缺少的是以下行

[httpclient setParameterEncoding:AFJSONParameterEncoding];