引入Google的gson jar
com.google.code.gson gson 2.8.0
使用
/** * 定义比较规则 * * @return */ private static ComparatorgetComparator() { return (s1, s2) -> s1.compareTo(s2); } /** * 排序 * * @param e */ public static void sort(JsonElement e) { if (e.isJsonNull() || e.isJsonPrimitive()) { return; } if (e.isJsonArray()) { JsonArray a = e.getAsJsonArray(); Iterator it = a.iterator(); it.forEachRemaining(i -> sort(i)); return; } if (e.isJsonObject()) { Map tm = new TreeMap<>(getComparator()); for (Map.Entry en : e.getAsJsonObject().entrySet()) { tm.put(en.getKey(), en.getValue()); } String key; JsonElement val; for (Map.Entry en : tm.entrySet()) { key = en.getKey(); val = en.getValue(); e.getAsJsonObject().remove(key); e.getAsJsonObject().add(key, val); sort(val); } } } /** * 根据json key排序 * @param json * @return */ private static String sortJson(String json) { Gson g = new GsonBuilder().setPrettyPrinting().create(); JsonParser p = new JsonParser(); JsonElement e = p.parse(json); sort(e); return g.toJson(e); } public static void main(String[] args) { String json = "{" + " \"aaa\":\"aaa\"," + " \"bbb\":\"bbb\"," + " \"abc\":\"abc\"," + " \"baa\":{" + " \"cab\":\"cab\"," + " \"abc\":\"abc\"," + " \"bac\":\"bac\"" + " }" + "}"; System.out.println(sortJson(json));; }