I have an android app posting to my sinatra service. Earlier I was not able to read parameters on my sinatra service. However, after I set content type to "x-www-form-urlencoded". I was able to see params but not quite how I wanted. I am getting something this as my params of the request at my sinatra service.
{"{\"user\":{\"gender\":\"female\"},\"session_id\":\"7a13fd20-9ad9-45c2-b308-
8f390b4747f8\"}"=> nil, "splat"=>["update_profile.json"], "captures"=>["update_profile.json"]}
This is how I am making request from my app.
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;
}
I tried using the method given by:How to make a nested Json object in Java?
This is how I made my request using the method mentioned in the link.
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;
}
The response I got after making the above change was this:
{"session_id"=>"958c7dee-f12c-49ec-ab0c-932e9a4ed173",
"user"=>"[gender=male]",
"splat"=>["update_profile.json"],
"captures"=>["update_profile.json"]}
Pretty close but that "gender=male" is not desirable. I need to pass these arguments to another service blindly, so I need to get them right.
The params that I want at my sinatra service are following.
{"session_id" : "958c7dee-f12c-49ec-ab0c-932e9a4ed173",
"user":
{
"gender" : "male"
}
}