Ray*_* A. 5 java android json android-volley
我正在尝试使用 JSONObjectRequest 将嵌套的 JSONObject 发送到服务器。服务器需要以下形式的 JSONObject:
{
"commit":"Sign In",
"user":{
"login":"my username",
"password":"mypassword"
}
}
Run Code Online (Sandbox Code Playgroud)
但目前我的程序正在通过以下 ( jsonObject.tostring())
{
"commit":"Sign In",
"user":" {
\"login\”:\”myusername\”,
\”password\”:\”mypassword\”
} ”
}
Run Code Online (Sandbox Code Playgroud)
JSONObjects 是由:
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,...)
Run Code Online (Sandbox Code Playgroud)
如何以上面的形式发送 JSONObject?
这是你的错误:
paramsForJSON.put("user", userJSONObject.toString().replaceAll("\\\\", ""));
Run Code Online (Sandbox Code Playgroud)
你已经把用户变成了String你不需要的用户,只需这样做:
loginRequestJSONObject.put("user", userJSONObject);
Run Code Online (Sandbox Code Playgroud)
尽管您已经完成了此操作,但实际上您已经获得了正确的行,这就是您所需要的:
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;
Run Code Online (Sandbox Code Playgroud)