是否可以使用AFNetworking AFHTTPRequestOperationManager方法发布一个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) {
}];
答案 0 :(得分:0)
您可以使用此自定义方法实现此目的:
- (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"];
答案 1 :(得分:0)
我试图将对象发送到服务但是jSON没有到达RESTful服务,我缺少的是跟随行
[httpclient setParameterEncoding:AFJSONParameterEncoding];