在我们拿到一团未经格式化的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));
}
}
运行后效果文章来源:https://www.toymoban.com/news/detail-796445.html
文章来源地址https://www.toymoban.com/news/detail-796445.html
到了这里,关于Java工具类——json字符串格式化处理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!