我正在尝试使用以下内容对一些数据进行编码:
NSDictionary *mydata = @{@"user": @{@"uuid" : tfUUID.text,
@"username" : tfUserName.text,
@"email" : tfEmailAddress.text,
@"password" : tfPassword.text,
@"password_confirmation" : tfPasswordConfirm.text}
};
NSData *sentData = [NSJSONSerialization dataWithJSONObject:mydata options:0 error:nil];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:sentData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *returnedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"Error is: %@", error);
NSDictionary *returnedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"The data I have received back is: %@", returnedData);
}];
然后我使用 POST/PUT 请求将其发送到 Rails 后端。
发送时,rails 服务器报告找不到名为“user”的参数。
我看到的输出是:
Started POST "/users" for 127.0.0.1 at 2013-12-18 12:16:20 +1100
Processing by UsersController#create as JSON
Parameters: {"{\"user\":{\"password\":\"********\",\"uuid\":\"********\",\"username\":\"********\",\"email\":\"********\",\"password_confirmation\":\"********\"}}"=>"[FILTERED]"}
Completed 400 Bad Request in 1ms
ActionController::ParameterMissing (param not found: user):
app/controllers/users_controller.rb:106:in `user_params'
app/controllers/users_controller.rb:42:in `create'
也许括号和反斜杠太多了?
根据rails(当我使用Web前端来实现相同的目的时,它是“期望的”:
Parameters: {"user"=>{"uuid"=>"*******", "username"=>"*******", "email"=>"*******", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Register"}
我在 Objective-C 中的 JSON 编码中做错了什么吗?
这让我很困惑,希望得到任何建议!
预先感谢您的帮助
最佳答案
问题似乎在于设置 NSURLSession。
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.timeoutIntervalForRequest = 30.0;
sessionConfig.timeoutIntervalForResource = 60.0;
sessionConfig.HTTPMaximumConnectionsPerHost = 1;
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig
delegate:self
delegateQueue:nil];
我有另外两行作为 sessionConfig 代码的一部分:
[sessionConfig setHTTPAdditionalHeaders:@{@"Accept": @"application/json"}];
[sessionConfig setHTTPAdditionalHeaders:@{@"Content-Type": @"application/json"}];
当我删除它们并将它们放入 NSURLMutableRequest 中时:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:homeURL];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
第一次就成功了。
必须承认我不知道为什么这不起作用......如果有人能启发我,我将不胜感激。
但我现在可以继续解决下一个问题。
关于ios - 从 iOS 发送 JSON 到 Rails 时括号过多( Objective-C ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20648278/