引入Google的gson jar
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
使用
/**
* 定义比较规则
*
* @return
*/
private static Comparator<String> getComparator() {
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<JsonElement> it = a.iterator();
it.forEachRemaining(i -> sort(i));
return;
}
if (e.isJsonObject()) {
Map<String, JsonElement> tm = new TreeMap<>(getComparator());
for (Map.Entry<String, JsonElement> en : e.getAsJsonObject().entrySet()) {
tm.put(en.getKey(), en.getValue());
}
String key;
JsonElement val;
for (Map.Entry<String, JsonElement> 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));;
}