效果
代码
@Test
public void test() {
JSONObject jsonObject = new JSONObject(true);
jsonObject.put("a","123");
jsonObject.put("db","11");
jsonObject.put("dd","asdasd");
jsonObject.put("b1","123123");
System.out.println(jsonObject.toJSONString());
System.out.println(json2pathValue(jsonObject));
}
/**
* JSON对象转为网址传参格式(按key的首字母从小到大排序)
* @param jsonObject
* @return
*/
public String json2pathValue(JSONObject jsonObject){
Map map = jsonObject.toJavaObject(Map.class);
Set<String> set = map.keySet();
List<String> keyList = new ArrayList<>(set);
List<String> collect = keyList.stream().sorted().collect(Collectors.toList());
StringBuilder stringBuilder = new StringBuilder();
for (String s : collect) {
stringBuilder.append(s).append("=").append(map.get(s).toString()).append("&");
}
stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
return stringBuilder.toString();
}