gpt4 book ai didi

iOS POST 到 Rails JSON 转义不正确

转载 作者:行者123 更新时间:2023-11-29 12:08:20 25 4
gpt4 key购买 nike

我正在尝试从我的 iOS 应用向我的本地主机服务器发帖。

正确执行此 curl 命令发布(JSON 是从我的 iOS 应用程序生成的字符串中复制的):

curl -XPOST -H "Content-Type: application/json" -d '{"appuser":{"id":0,"birthday_month":2,"hispanic_origin":"0","marital_status":"1","age":25,"idfa":"A84F55A7-3C6F-4A2E-9379-AB9895863C25","profiled":1,"dob":"2\/16\/1989","quality":1,"zip":"53593","device_type":"x86_64","income":"7","race":"0","children":"36","birthday_year":1989,"education":"7","employment_status":"0","gender":0,"birthday_day":16}}' http://localhost:3000/api/v1/appusers?access_token=6434ba7036431f2c8d12572eab0f2746

在我的 iOS 应用程序中,我创建了这样的 POST:

NSString *urlStr = [@"http://localhost:3000/api/v1/appusers?access_token=" stringByAppendingString:[NSString stringWithFormat:@"6434ba7036431f2c8d12572eab0f2746"]];

NSURL *url = [NSURL URLWithString:urlStr];

NSURLSession *session = [NSURLSession sharedSession];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

request.HTTPBody = [newNewString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {


}];
[postDataTask resume];

但我不断从我的服务器收到 400 响应:

ActionController::ParameterMissing (param is missing or the value is empty: appuser):
app/controllers/api/v1/appusers_controller.rb:36:in `appuser_params'
app/controllers/api/v1/appusers_controller.rb:10:in `create'

问题似乎在于 JSON 在发送到我的 Rails 应用程序之前是如何转义的。在我的服务器中它看起来像这样:

Parameters: {"{\"appuser\":`{\"id\":0,\"birthday_month\":2,\"hispanic_origin\":\"0\",\"marital_status\":\"1\",\"age\":25,\"idfa\":\"A84F55A7-3C6F-4A2E-9379-AB9895863C25\",\"profiled\":1,\"dob\":\"2\\/16\\/1989\",\"quality\":1,\"zip\":\"53593\",\"device_type\":\"x86_64\",\"income\":\"7\",\"race\":\"0\",\"children\":\"36\",\"birthday_year\":1989,\"education\":\"7\",\"employment_status\":\"0\",\"gender\":0,\"birthday_day\":16}}"=>nil, "access_token"=>"6434ba7036431f2c8d12572eab0f2746"}`

但是当我在我的应用程序中注销它时,我看到了这个:

{"appuser":{
"id" : 0,
"birthday_month" : 2,
"hispanic_origin" : "0",
"marital_status" : "1",
"age" : 25,
"idfa" : "A84F55A7-3C6F-4A2E-9379-AB9895863C25",
"profiled" : 1,
"dob" : "2\/16\/1989",
"quality" : 1,
"zip" : "53593",
"device_type" : "x86_64",
"income" : "7",
"race" : "0",
"children" : "36",
"birthday_year" : 1989,
"education" : "7",
"employment_status" : "0",
"gender" : 0,
"birthday_day" : 16
}}

我还尝试去除换行符和空格以在我的 iOS 应用程序中得到它:

{"appuser":{"id":0,"birthday_month":2,"hispanic_origin":"0","marital_status":"1","age":25,"idfa":"A84F55A7-3C6F-4A2E-9379-AB9895863C25","profiled":1,"dob":"2\/16\/1989","quality":1,"zip":"53593","device_type":"x86_64","income":"7","race":"0","children":"36","birthday_year":1989,"education":"7","employment_status":"0","gender":0,"birthday_day":16}}

我的直觉告诉我问题出在我对字符串进行编码的地方:

request.HTTPBody = [newNewString dataUsingEncoding:NSUTF8StringEncoding];

这是我创建 JSON 的方式:

NSMutableDictionary *appuserDictionary = [NSMutableDictionary dictionary];

NSEntityDescription *entity = [self.appuser entity];
NSDictionary *attributes = [entity attributesByName];
for (NSString *attribute in attributes) {
id attributeValue = [self.appuser valueForKey: attribute];
if (attributeValue) {
[appuserDictionary setObject:attributeValue forKey:attribute];
}
}

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:appuserDictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];

if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *appuserJsonString = [NSString stringWithFormat:@"{%@:%@}", @"\"appuser\"", jsonString];

NSString *newString = [[appuserJsonString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];
NSString *newNewString = [[newString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]] componentsJoinedByString:@""];
NSLog(appuserJsonString);
NSLog(newNewString);

我是 iOS 的新手,希望我只是遗漏了一些愚蠢的东西。

还有我的 Rails Controller (ApiController 基本上只是验证 access_token):

module Api
module V1
class AppusersController < ApiController

def show
@appuser = Appuser.find(params[:id])
end

def create
@appuser = Appuser.new(appuser_params)

respond_to do |format|
if @appuser.save
@appuser.update_location
format.json { render action: 'show', status: :created, location: @appuser }
else
format.json { render json: @appuser.errors, status: :unprocessable_entity }
end
end
end

def update
@appuser = Appuser.find(params[:id])
respond_to do |format|
if @appuser.update(appuser_params)
format.json { head :no_content }
else
format.json { render json: @appuser.errors, status: :unprocessable_entity }
end
end
end

private
# Never trust parameters from the scary internet, only allow the white list through.
def appuser_params
params.require(:appuser).permit(:age, :income, :city, :zip, :county, :state, :state_code, :country, :gender, :employment_status, :education, :marital_status, :email, :username, :remember_token, :created_at, :updated_at, :coins, :pending_coins, :userGo, :birthday_month, :birthday_day, :birthday_year, :profiled, :quality, :race, :children, :hispanic_origin)
end
end
end
end

最佳答案

您必须通过添加正确的请求 header 来告诉服务器您的正文是 JSON 格式:

...
request.HTTPBody = [newNewString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
...

关于iOS POST 到 Rails JSON 转义不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34258826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com