如何在调用任何 api 时将 post 参数作为 android 中的 json

how to post parameters as a json in android while calling any api

我是 Android 开发的新手,我需要在调用任何 API 方法时将 post 参数作为 JSON。

我作为数组列表传递:

List<NameValuePair> params = new ArrayList<NameValuePair>();

请提出任何建议。 谢谢

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


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

我终于找到了使用 volley 库的解决方案,现在工作正常

  private void callApiWithJsonReqPost() {
        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=new JSONObject();
        jsonObject.put("address", uAddress);
        jsonObject.put("type", "insert");
        jsonObject.put("tag", addressTag);

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


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

                @Override
                public void onResponse(JSONObject response) {
                    Log.d("new_address" ,"sons=="+response.toString());

                }
            }, new Response.ErrorListener() {

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

        }
    }) {

        /**
         * Passing some request headers
         * */
        @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;
        }


    };

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


}

我在 Android http://github.com/amirdew/JSON

中编写了一个用于解析和生成 JSON 的库

例如:

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


  String jsonString = generatedJsonObject.toString();

结果:

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