Send nested JSON without Escape character

I am trying to send a nested JSONObject to the server using JSONObjectRequest. The server expects a JSONObject in the form:

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

but currently my program sends the following messages ( jsonObject.tostring())

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

JSONO objects are created:

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 to submit JSONObject to the form above?

+4
source share
1 answer

This is your mistake:

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

You have turned the user into Stringone that you do not need, just do the following:

loginRequestJSONObject.put("user", userJSONObject);

Although you have already done this, you actually have the correct lines, that’s 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;
+1
source

Source: https://habr.com/ru/post/1670199/


All Articles