2017-08-10 71 views
0

我想使用volley库发送嵌套后的json参数,请帮助我。我能够以简单的json格式发送帖子参数,但是在嵌套json的情况下,如何做到这一点?如何发送嵌套的JSON作为android volley库中的post参数

即。 { "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

发表您的凌空请求的代码。 –

+0

把jsonarray,而不是jsonobject –

+0

这个链接可能会帮助你https://stackoverflow.com/questions/35895134/post-nested-json-object-to-server-using-volley-getting-response-200 –

回答

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; 
} 

并添加到您的凌空JSON请求对象

try{ 
    JSONObject requestObject =new JSONObject(); 
    requestObject.put("yourParamName",getJsonObject("martin","20")); 
}catch(JSONException e){ 

} 
+0

是的,它的工作。 –

+0

@SubhashisRouth如果有效请使用旁边的复选标记接受答案 – akhilesh0707

相关问题