java实现json字符串格式化处理的工具类
作者:陈皮太
这篇文章主要为大家详细介绍了如何使用java实现json字符串格式化处理的工具类,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下
在我们拿到一团未经格式化的json字符串时,非常不方便查看,比如这样
{"APP_HEAD": {"TOTAL_NUM": "-1","PGUP_OR_PGDN": "0"},"SYS_HEAD": {"RET": [{"RET_CODE": "000000","RET_MSG": "000000 SUCCESS"},{"RET_CODE": "000001","RET_MSG": "000001 SUCCESS"}],"AUTH_USER_ID": null,"RUN_DATE": "20211222","MESSAGE_CODE": "369285","SOURCE_BRANCH_NO": "142857"},"BODY": [{"createDate":"20220630","fileName":"RB_TRAN_HIST_20220630_2_1.txt","filePath":"/acc/abcd/20220630","fileScence":"abcd","fileType":"txt","systemId":"ACC"},{"createDate":"20220630","fileName":"RB_TRAN_HIST_20220630_2_2.txt","filePath":"/acc/abcd/20220630","fileScence":"abcd","fileType":"txt","systemId":"ACC"}]}
因此随手写了个工具类用来格式化json。注意,原json字符串必须语法无误,并且不包含换行、空格、缩进等,否则会保留下来。
ok废话不多说上代码
package com.xxx.util; /** * json字符串格式化 * @AuThor wangbyn */ public class JsonUtil { public static String format(String jsonStr) { int level = 0; StringBuffer jsonForMatStr = new StringBuffer(); for (int i = 0; i < jsonStr.length(); i++) { char c = jsonStr.charAt(i); if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) { jsonForMatStr.append(getLevelStr(level)); } switch (c) { case '{': case '[': jsonForMatStr.append(c).append("\n"); level++; break; case ',': jsonForMatStr.append(c).append("\n"); break; case '}': case ']': jsonForMatStr.append("\n"); level--; jsonForMatStr.append(getLevelStr(level)); jsonForMatStr.append(c); break; default: jsonForMatStr.append(c); break; } } return jsonForMatStr.toString(); } private static String getLevelStr(int level) { StringBuffer levelStr = new StringBuffer(); for (int levelI = 0; levelI < level; levelI++) { levelStr.append("\t"); } return levelStr.toString(); } public static void main(String[] args) { String json = "{\"APP_HEAD\": {\"TOTAL_NUM\": \"-1\",\"PGUP_OR_PGDN\": \"0\"},\"SYS_HEAD\": {\"RET\": [{\"RET_CODE\": \"000000\",\"RET_MSG\": \"000000 SUCCESS\"},{\"RET_CODE\": \"000001\",\"RET_MSG\": \"000001 SUCCESS\"}],\"AUTH_USER_ID\": null,\"RUN_DATE\": \"20211222\",\"MESSAGE_CODE\": \"369285\",\"SOURCE_BRANCH_NO\": \"142857\"},\"BODY\": [{\"createDate\":\"20220630\",\"fileName\":\"RB_TRAN_HIST_20220630_2_1.txt\",\"filePath\":\"/acc/abcd/20220630\",\"fileScence\":\"abcd\",\"fileType\":\"txt\",\"systemId\":\"ACC\"},{\"createDate\":\"20220630\",\"fileName\":\"RB_TRAN_HIST_20220630_2_2.txt\",\"filePath\":\"/acc/abcd/20220630\",\"fileScence\":\"abcd\",\"fileType\":\"txt\",\"systemId\":\"ACC\"}]}"; System.out.println(format(json)); } }
运行后效果
到此这篇关于java实现json字符串格式化处理的工具类的文章就介绍到这了,更多相关java格式化json内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!