Bivin Bivin - 3 months ago 25
JSON Question

posting params as json in android volley

I am using volley library for making request. I need to post param as json array because I am receiving it on the other side as json array. How can I convert my params to Json array?
here is my code

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

}


please help..

Answer
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);
}
Comments