Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Nested JSON Object without Escape Character

I'm trying to send a nested JSONObject to a server using JSONObjectRequest. The server is expecting a JSONObject in the form of:

{  
   "commit":"Sign In",
   "user":{  
      "login":"my username",
      "password":"mypassword"
   }
}

but currently my program is sending through the following (jsonObject.tostring())

{  
   "commit":"Sign In",
   "user":"   {  
      \"login\”:\”myusername\”,
      \”password\”:\”mypassword\”
   }   ”
}

The JSONObjects are made by:

final JSONObject loginRequestJSONObject = new JSONObject();
final JSONObject userJSONObject = new JSONObject();
userJSONObject.put("login", "myuser");
userJSONObject.put("password", "mypass");

loginRequestJSONObject.put("user", userJSONObject);
loginRequestJSONObject.put("commit", "Sign In");
Map<String, String> paramsForJSON = new HashMap<String, String>();
paramsForJSON.put("user", userJSONObject.toString().replaceAll("\\\\", "");
paramsForJSON.put("commit", "Sign In");
JSONObject objectToSend =  new JSONObject(paramsForJSON);

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, objectToSend,...)

How can I send a JSONObject in the form above?

like image 544
Ray A. Avatar asked Nov 09 '22 01:11

Ray A.


1 Answers

This is your error:

paramsForJSON.put("user", userJSONObject.toString().replaceAll("\\\\", ""));

You've turned the user into a String you don't need to, just do this:

loginRequestJSONObject.put("user", userJSONObject);

Though you've already done this, you've actually got the correct lines in there, this is all you need:

final JSONObject loginRequestJSONObject = new JSONObject();
final JSONObject userJSONObject = new JSONObject();
userJSONObject.put("login", "myuser");
userJSONObject.put("password", "mypass");

loginRequestJSONObject.put("user", userJSONObject);
loginRequestJSONObject.put("commit", "Sign In");

JSONObject objectToSend = loginRequestJSONObject;
like image 100
weston Avatar answered Nov 14 '22 23:11

weston