【Java】json排序/根据key排序/不限层级/字母排序
一、需求
对JSON的key根据首字母排序 若首字母相同对比下一个字母 依次类推
二、效果
三、代码
maven
<dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.79</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> </dependencies>
代码
import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; /** * @Author: 维斯 * @Date: 2022/6/30 14:55 * @Description: Json排序工具 * @Version: v1.0 */ public class JsonSortUtil { /** * 对单词列表进行冒泡排序 * 直接操作对象地址 无需返回 * * @param words ["name","age"] */ private static void wordSort(ArrayList<String> words) { for (int i = words.size() - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (words.get(j).compareToIgnoreCase(words.get(j + 1)) > 0) { String temp = words.get(j); words.set(j, words.get(j + 1)); words.set(j + 1, temp); } } } } /** * 对单层json排序 * * @param json */ private static JSONObject getAloneKeys(JSONObject json) { ArrayList<String> aloneKeys = new ArrayList<>(); for (String key : json.keySet()) { aloneKeys.add(key); } // 排序 JsonSortUtil.wordSort(aloneKeys); // 整理排序后的json JSONObject newJson = new JSONObject(new LinkedHashMap<>()); for (String key : aloneKeys) { newJson.put(key, json.get(key)); } return newJson; } /** * 递归每一层(当前是判断下一层是JSONObject类型的场景) * * @param json * @return */ private static JSONObject getAloneKeysRec(JSONObject json) { JSONObject newJson = getAloneKeys(json); for (Map.Entry<String, Object> entry : newJson.entrySet()) { // JSONObject类型 if (entry.getValue().getClass().equals(JSONObject.class)) { newJson.put(entry.getKey(), getAloneKeysRec((JSONObject) entry.getValue())); } } return newJson; } /** * 对JSONObject的key根据首字母排序 若首字母相同对比下一个字母 依次类推 * 备注:当前未覆盖JSONArray的场景 * * @param json * @return 排序后的新json */ public static JSONObject startSort(JSONObject json) { // 第1层 JSONObject jsonAlone = getAloneKeys(json); // 第2-n层 for (Map.Entry<String, Object> entry : jsonAlone.entrySet()) { // 这里仅判断JSONObject类型的场景(若需要覆盖JSONArray场景 对应添加即可) if (entry.getValue().getClass().equals(JSONObject.class)) { jsonAlone.put(entry.getKey(), getAloneKeysRec((JSONObject) entry.getValue())); } } return jsonAlone; } public static void main(String[] args) { String jsonStr = "{\"code\":200,\"message\":\"success\",\"data\":{\"bate\":\"bate值\",\"baae\":{\"case\":\"case值\",\"casa\":{\"ask\":\"ask值\",\"bsk\":{\"abcdefghijklmn\":\"abcdefghijklmn值\",\"abcdefghijklma\":\"abcdefghijklma值\"}}}}}\n"; System.out.println(String.format("排序前:%s", jsonStr)); System.out.println(String.format("排序后:%s", JsonSortUtil.startSort((JSONObject) JSONObject.parse(jsonStr)))); } }
四、测试数据
以下是乱序的json
json1
{"rgubr":"rgubr值","rgubb":{"wenqo":"wenqo值","cwnnr":"cwnnr值","vkpid":"vkpid值","rwula":{"ieeho":"ieeho值","ujvwa":{"ismuo":"ismuo值","eydil":"eydil值","emkfm":"emkfm值","cksdv":{"aaaaa":"aaaaa值","bceef":"bceef值","bcdef":"bcdef值","acbdf":"acbdf值","acbde":"acbde值"},"viriy":"viriy值"},"corby":"corby值","tljbn":"tljbn值","fvjtd":"fvjtd值"},"xdfmy":"xdfmy值"},"lrirp":"lrirp值","ttaae":"ttaae值","nefab":"nefab值"}
json2
{"code":200,"message":"sucess","data":{"id":1885,"recordType":2,"isSelfSeat":1,"isRemote":1,"isScene":1,"virtualSeatBid":1,"isHead":1,"screenPosition":2,"isBroadCast":1,"speechSpeed":1.0,"remoteVoiceType":3,"isBaseCheck":1,"isForceCheck":0,"isAuditionTest":1,"isForceDebug":0,"paraGraph":2,"isPersonQuality":1,"processBid":12461,"bid":2885,"status":0,"createId":11636,"updateId":11636,"updateTime":"2022-06-16 10:50:48","createTime":"2022-06-13 16:57:51","merchantVirtualPortrait":{"bid":1,"status":1,"merchantBid":0,"name":"女坐席","anchorType":"单人主播","speechRate":100,"volume":50,"voice":3,"sex":2,"ttsText":"这是测试女生tts语音","virtualPortraitFiles":""},"isGeneralRule":1,"isSelfSeatLocation":1,"isRemoteLocation":1,"isSceneLocation":1,"isFaceLocation":0,"isVirtualSeat":1,"watermarkSwitch":1,"watermarkRecordingBid":25,"watermarkSynthesisBid":26,"watermarkRecording":{"bid":25,"name":"录制时-图片水印","type":2,"text":"","position":1,"transparency":100,"fileId":"2b5c68ce85d74f0ebd16a4e428e63e18","sourceFileId":"b007bf9c97b54557a3fcd5c9fc4f483f","applyStage":1,"waterDate":2,"fontSize":14,"fontColor":"#000000","horizontalOffset":15,"verticalOffset":15,"width":120,"height":80},"watermarkSynthesis":{"bid":26,"name":"合成-图片","type":2,"text":"","position":1,"transparency":100,"fileId":"672b8f50a9d34da0b0c3c8fafb27e39b","sourceFileId":"9de58743be514e68af24a9d92d348e88","applyStage":2,"waterDate":2,"fontSize":14,"fontColor":"#000000","horizontalOffset":15,"verticalOffset":15,"width":120,"height":80}},"success":true}
json3
{"code":200,"message":"sucess","data":{"id":1885,"recordType":2,"merchantVirtualPortrait":{"bid":1,"status":1,"merchantBid":0,"name":"女坐席","anchorType":"单人主播","datab":{"datac":{"datac":{"ssa":"asdf","asdfa":{"asdfa":"asdfas","asdfdfasd":{"asdf":"asdfasf"}}}}},"databb":"databb"}},"isGeneralRule":1,"isSelfSeatLocation":1,"isRemoteLocation":1,"isSceneLocation":1,"isFaceLocation":0,"isVirtualSeat":1,"watermarkSwitch":1,"watermarkRecordingBid":25,"watermarkSynthesisBid":26,"success":true}
json4
{"code":200,"message":"success","data":{"bate":"bate值","baae":{"case":"case值","casa":{"ask":"ask值","bsk":{"abcdefghijklmn":"abcdefghijklmn值","abcdefghijklma":"abcdefghijklma值"}}}}}
如果忍耐算是坚强 我选择抵抗 如果妥协算是努力 我选择争取