简体   繁体   English

iOS POST到Rails JSON的转义错误

[英]iOS POST to Rails JSON Escaped Incorrectly

I'm attempting to do a post to my localhost server from my iOS app. 我正在尝试从我的iOS应用发布到本地服务器的帖子。

Doing this curl command posts correctly (the JSON was copied from the string generated on my iOS app): 正确执行以下curl命令(从我的iOS应用程序生成的字符串中复制了JSON):

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

In my iOS app I create the POST like this: 在我的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];

But I continually get a 400 response from my server stating: 但是我不断从服务器收到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'

The problem seems to be with how the JSON was escaped before sent to my rails app. 问题似乎与在发送到我的rails应用之前如何转义JSON有关。 In my server it looks like this: 在我的服务器中,它看起来像这样:

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"}`

But when I log it out in my app I see this: 但是,当我在应用程序中将其注销时,会看到以下内容:

{"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
}}

I also tried stripping the newlines and spaces to get this in my iOS app: 我还尝试剥离换行符和空格,以将其添加到我的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}}

My gut feeling says the problem lies here where I encode the string: 我的直觉表明问题出在我编码字符串的地方:

request.HTTPBody = [newNewString dataUsingEncoding:NSUTF8StringEncoding];

Here's how I'm creating my JSON: 这是我创建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);

I'm new to iOS so hopefully I'm just missing something stupid. 我是iOS的新手,所以希望我只是想念一些愚蠢的东西。

And my Rails controller (ApiController basically just validates the access_token): 还有我的Rails控制器(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

You have to tell the server that your body is in a JSON format by adding the right request header: 您必须通过添加正确的请求标头来告知服务器您的正文为JSON格式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM