java中調用三方接口post傳參時map和jsonobject的區別轉換

post方法名及參數爲:(具體方法可參考http://www.javashuo.com/article/p-nseguyln-a.html)html

  public static String doPost(String httpUrl, String param) {   ...   }

若是方法參數param是要求以json字符串的形式傳遞則:json

  1. 若是是JSONObject對象轉字符串則:String result = HttpUtil.doPost(URL, json.toJsonString());post

  2. Map轉字符串則需採用:String result = HttpUtil.doPost(URL, JSON.toJSONString(map));測試

  注:使用map.toString() 時會出現參數解析不到的問題spa

  由於:json.toJsonString()轉換後爲:{"name":"ceshi","password":"123456"}code

     map.toString()轉換後爲:{password=123456, name=ceshi}htm

  對比可知,參數不一致;對象

 

測試以下:blog

  public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("name", "ceshi");
        map.put("password", "123456");
        System.out.println(map.toString()); //{password=123456, name=ceshi}
        System.out.println(JSON.toJSONString(map)); //{"name":"ceshi","password":"123456"}

        JSONObject json = new JSONObject();
        json.put("name", "ceshi");
        json.put("password", "123456");
        System.out.println(json.toJSONString()); //{"name":"ceshi","password":"123456"}
    }
相關文章
相關標籤/搜索