Skip to content Skip to sidebar Skip to footer

How To Post Parameters As A Json In Android While Calling Any Api

I am new to Android development, I need to post parameters as a JSON while calling any API method. I am passing as a array list: List params = new ArrayList<

Solution 1:

finally i found solution using volley library, it's working fine now

privatevoidcallApiWithJsonReqPost() {
        boolean failure = false;
        uAddress="133 Phùng Hưng, Cửa Đông, Hoàn Kiếm, Hà Nội, Vietnam";
       addressTag="work address";
        String callingURl="put your url here"JSONObject jsonObject=null;

    try {
         jsonObject=newJSONObject();
        jsonObject.put("address", uAddress);
        jsonObject.put("type", "insert");
        jsonObject.put("tag", addressTag);

    } catch (Exception e) {
        e.printStackTrace();
    }


    JsonObjectRequest jsonObjReq = newJsonObjectRequest(Method.POST,
            callingURl, jsonObject,
            newResponse.Listener<JSONObject>() {

                @OverridepublicvoidonResponse(JSONObject response) {
                    Log.d("new_address" ,"sons=="+response.toString());

                }
            }, newResponse.ErrorListener() {

        @OverridepublicvoidonErrorResponse(VolleyError error) {
            VolleyLog.d("error", "Error: " + error.getMessage());

        }
    }) {

        /**
         * Passing some request headers
         * */@OverridepublicMap<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = newHashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;
        }


    };

    // Adding request to request queueSingleton_volley.getInstance().addToRequestQueue(jsonObjReq,"1");


}

Solution 2:

params.add(new BasicNameValuePair("key",data)); 


JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

Solution 3:

I wrote a library for parsing and generating JSON in Android http://github.com/amirdew/JSON

for example:

JSON generatedJsonObject = JSON.create(
                JSON.dic(
                        "someKey", "someValue",
                        "someArrayKey", JSON.array(
                                "first",
                                1,
                                2,
                                JSON.dic(
                                        "emptyArrayKey", JSON.array()
                                )
                        )
                )
        );


  String jsonString = generatedJsonObject.toString();

result:

{"someKey":"someValue","someArrayKey":["first",1,2,{"emptyArrayKey":[]}]}

Post a Comment for "How To Post Parameters As A Json In Android While Calling Any Api"