在android volley中发送params作为json

时间:2016-08-05 12:22:16

标签: android json android-volley

我正在使用排球库提出请求。我需要将param作为json数组发布,因为我在另一端接收它作为json数组。如何将params转换为Json数组? 这是我的代码

 public void SendData() {{
    final StringRequest strReq = new StringRequest(Request.Method.POST, GET_STUDENTS_BY_ID, new Response.Listener<String>() {

            @Override
        public void onResponse(String response) {


                Log.v("failedd",response);
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Error", "Registration Error: " + error.getMessage());

        }
    })

    {
        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url


            Map<String, String> params = new HashMap<String, String>();

            params.put("user_id", user_id);

            params.put("student_id", studId);
            params.put("to", tomail);
            params.put("subject", subjects);
            params.put("description", descriptions);
             return params;

        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;
        }
    };

    AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);

}

请帮助..

1 个答案:

答案 0 :(得分:1)

public void SendData() {

   Map<String, String> params = new HashMap<String, String>();

        params.put("user_id", user_id);
        params.put("student_id", studId);
        params.put("to", tomail);
        params.put("subject", subjects);
        params.put("description", descriptions);

  JSONObject parameters = new JSONObject(params);

  JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,GET_STUDENTS_BY_ID,parameters,new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        }) {

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        return headers;
    }

 };

    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}