需求是這樣
我們需要發送一個post請求向服務器要參數。要求是發送的post參數也要是json格式。
簡單一點的是這樣的:
如果要發送的是這樣簡單的json格式,我們可以簡單的使用map來實現:


RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());Map<String, String> merchant = new HashMap<String, String>();merchant.put("id", "id");merchant.put("ncode", "ncode");merchant.put("tradingName", "tradingName");Log.d("map", map.toString());JSONObject jsonObject = new JSONObject(merchant);Log.e(TAG, "getdata: " + jsonObject.toString());JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST, "", jsonObject,new Response.Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {Log.d(TAG, "response -> " + response.toString());}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.e(TAG, error.getMessage(), error);}}) {@Overridepublic Map<String, String> getHeaders() {HashMap<String, String> headers = new HashMap<String, String>();headers.put("Accept", "application/json");headers.put("Content-Type", "application/json; charset=UTF-8");return headers;}};requestQueue.add(jsonRequest);}
這里主要用到的就是
JSONObject jsonObject = new JSONObject(map);
這個方法,可以很方便的將map轉成json數據。
如果需要傳的是個有嵌套的json數據又該怎么辦呢?
例如:
相比之前的數據,我們看到?merchant?也是一個json Object
這種嵌套的格式該怎么寫呢?也很簡單這里是嵌套,我們也寫一個map的嵌套
就好啦!


RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());Map<String, String> merchant = new HashMap<String, String>();merchant.put("id", "id");merchant.put("ncode", "ncode");merchant.put("tradingName", "tradingName");Map<String, Object> map = new HashMap<>();map.put("billType", "ADHOC");map.put("collectionCode", "string");map.put("otherRefNo", "string");map.put("contactMode", "SMS");map.put("merchant", merchant);map.put("currency", "SGD");map.put("amount", " 0.00");Log.d("map", map.toString());JSONObject jsonObject = new JSONObject(map); //后面一樣的,省略。
這樣再使用?JSONObject 的方法就可以生成我們想要的json格式啦!很簡單是吧。
?
下面來說下JsonRequest的參數:
參數一:
請求方式 (這里是post)
參數二:
請求的URL
參數三:
請求的參數(如果是get請求方式則為空 null)
參數四:
服務器相應的回調(可以根據服務器的相應碼區分不同的情況)
參數五:
服務器未響應的回調(可以做一些簡單的提示)
?
?
謝謝閱讀!
?