我想使用volley库发送嵌套的json参数,请帮帮我。我能够以简单的json格式发送post参数,但是在嵌套json的情况下,如何做到这一点?
即。
{
"user": {
"name": "Martin"
"age": "20"
}
}
这是我的代码:
JSONObject mainJson = new JSONObject();
JSONObject userJson = new JSONObject();
try {
userJson.put("first_name", firstname);
userJson.put("last_name", lastname);
userJson.put("email", email);
userJson.put("role", "consumer");
userJson.put("password", password);
mainJson.put("user", userJson);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, AppConfig.URL_SIGN_UP, mainJson, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG,response.toString());
Log.d("TAG","====================== SUCCESS ========================");
hideDialog();
goToLoginPage();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
hideDialog();
Log.d(TAG,error.toString());
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonRequest, TAG);
答案 0 :(得分:1)
试试这个来制作你的JSON
private JSONObject getJsonObject(String name, String age) throws JSONException {
JSONObject jsonObject = new JSONObject();
JSONObject userJson = new JSONObject();
userJson.put("name", name);
userJson.put("age", age);
jsonObject.put("user", userJson);
return jsonObject;
}
并添加到您的Volley JSON请求对象
try{
JSONObject requestObject =new JSONObject();
requestObject.put("yourParamName",getJsonObject("martin","20"));
}catch(JSONException e){
}