java 呼叫三方介面post傳參時map和jsonobject的區別
阿新 • • 發佈:2021-06-19
如果方法引數param是要求以json字串的形式傳遞則:
1. 如果是JSONObject物件轉字串則:String result = HttpUtil.doPost(URL,json.toJsonString());
2. Map轉字串則需採用:String result = HttpUtil.doPost(URL,JSON.toJSONString(map));
注:使用map.toString() 時會出現引數解析不到的問題
因為:json.toJsonString()轉換後為:{"name":"ceshi","password":"123456"}
map.toString()轉換後為:{password=123456, name=ceshi}
對比可知,引數不一致;
測試方法如下:
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"} }
參考:https://www.cnblogs.com/mufengforward/p/10707484.html