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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With