我有一个android应用发布到我的sinatra服务。之前我无法读取我的sinatra服务的参数。但是,在将内容类型设置为“x-www-form-urlencoded”之后。我能够看到参数,但不是我想要的。我将这件事作为我在sinatra服务中的要求的参数。从java发布JSON参数到sinatra服务
{"{\"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;
}
我试图使用给出的方法:How to make a nested Json object in Java?
这是我使用的链接中提到的方法做了我的请求。
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"]}
相当接近,但“性别=男”是不可取的。我需要盲目地将这些参数传递给另一个服务,所以我需要让它们正确。
我想在我的sinatra服务中的参数如下。
{"session_id" : "958c7dee-f12c-49ec-ab0c-932e9a4ed173",
"user":
{
"gender" : "male"
}
}
你可以尝试为application/json的ContentType? – Chris
我已经做了。在我的sinatra服务中看不到参数。尽管我可以使用request.body来阅读它们。阅读,但这似乎是一个解决方法。 – goyalankit
我不明白解释和问题是什么?你用了很多这个词,但我不知道你指的是什么。 – gigadot