将 JSON 参数从 java 发布到 sinatra 服务



我有一个安卓应用程序发布到我的Sinatra服务。早些时候,我无法读取我的 sinatra 服务上的参数。但是,在我将内容类型设置为"x-www-form-urlencoded"之后。我能够看到参数,但不是我想要的。我在我的辛纳屈服务中得到了一些作为请求的参数。

{"{"user":{"gender":"female"},"session_id":"7a13fd20-9ad9-45c2-b308-
8f390b4747f8"}"=> nil, "splat"=>["update_profile.json"], "captures"=>["update_profile.json"]}

这就是我从我的应用程序发出请求的方式。

StringEntity se;                    
se = new StringEntity(getJsonObjectfromNameValueList(params.get_params(), "user");
se.setContentType("application/x-www-form-urlencoded");
postRequest.setEntity(se);

private JSONObject getJsonObjectfromNameValueList(ArrayList<NameValuePair> _params, String RootName) {
    JSONObject rootjsonObject = new JSONObject();
    JSONObject jsonObject = new JSONObject();
    if (_params != null) {
        if (!_params.isEmpty()) {
            for (NameValuePair p : _params) {
                try {
                    if (p.getName().equals(ApplicationFacade.SESSION_ID))
                        rootjsonObject.put((String) p.getName(), (String) p.getValue());
                    else
                        jsonObject.put((String) p.getName(), (String) p.getValue());
                } catch (JSONException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
    }
    try {
        rootjsonObject.put(RootName, jsonObject);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return rootjsonObject;
}

我尝试使用给出的方法:如何在 Java 中制作嵌套的 Json 对象?

这就是我使用链接中提到的方法提出请求的方式。

public ArrayList<NameValuePair> getJsonObjectfromNameValueList(ArrayList<NameValuePair> _params, String RootName){
    ArrayList<NameValuePair> arrayList = new ArrayList<NameValuePair>();
    JSONObject jsonObject = new JSONObject();
    if (_params != null) {
        if (!_params.isEmpty()) {
            for (NameValuePair p : _params) {
                try {
                    if (p.getName().equals(ApplicationFacade.SESSION_ID))
                        arrayList.add(new BasicNameValuePair((String) p.getName(), (String) p.getValue()));
                    else
                        jsonObject.put((String) p.getName(), (String) p.getValue());
                } catch (JSONException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
    }
    arrayList.add(new BasicNameValuePair(RootName, jsonObject.toString()));
    return arrayList;
}

进行上述更改后我得到的回应是这样的:

{"session_id"=>"958c7dee-f12c-49ec-ab0c-932e9a4ed173",
"user"=>"[gender=male]",
 "splat"=>["update_profile.json"],
 "captures"=>["update_profile.json"]}

非常接近,但"性别=男性"是不可取的。我需要将这些参数盲目地传递给另一个服务,所以我需要将它们正确。

我想要在我的辛纳屈服务中的参数如下。

{"session_id" : "958c7dee-f12c-49ec-ab0c-932e9a4ed173",
 "user": 
 {
   "gender" : "male"
 }

}

事实证明,问题出在辛纳屈获取参数的方式上。我能够使用 Kyle 对这篇文章的出色回应来解决我的问题:Sinatra 控制器参数方法在 JSON 发布请求中为空

法典:

before do
  if request.request_method == "POST" and request.content_type=="application/json"
    body_parameters = request.body.read
    parsed = body_parameters && body_parameters.length >= 2 ? JSON.parse(body_parameters) : nil
    params.merge!(parsed)
  end
end

替代方法:但是,我找到了更好的解决方案来处理它,通过添加一个中间件为我做同样的事情。我用rack-contrib宝石。以下是我在代码中所做的更改:

编辑

使用 git 获取修复了与内容类型application/json;charset=UTF-8相关的问题的版本

宝石文件:

gem 'rack-contrib', git: 'git@github.com:rack/rack-contrib', ref: 'b7237381e412852435d87100a37add67b2cfbb63'

config.ru

use Rack::PostBodyContentTypeParser

来源: http://jaywiggins.com/2010/03/using-rack-middleware-to-parse-json/

使用以下内容对我来说效果更好。我不得不添加request.body.rewind和:symbolize_names => true(同时调用JSON.parse(

before do
  if request.request_method == "POST" and (request.content_type || '').include? "application/json" 
    request.body.rewind
    body_parameters = request.body.read
    parsed = body_parameters && body_parameters.length >= 2 ? JSON.parse(body_parameters, :symbolize_names => true) : nil
    params.merge!(parsed)
  end
end

最新更新