package com.hdkj.lt.utils.serialize;

/**
 * @Description:
 * @Author: wenhao
 * @Create: 2022/11/02 9:36
 * @Version: 1.0
 */
public class JsonUtils {

    private JsonUtils() {
    }

    public static String formatJson(String jsonString) {
        // 计数tab的个数
        int tabNum = 0;
        StringBuilder jsonFormat = new StringBuilder();
        int length = jsonString.length();
        for (int i = 0; i < length; i++) {
            char c = jsonString.charAt(i);
            if (c == '{' || c == '[') {
                tabNum++;
                jsonFormat.append(c).append("\n").append(getSpaceOrTab(tabNum));
            } else if (c == '}' || c == ']') {
                tabNum--;
                jsonFormat.append("\n").append(getSpaceOrTab(tabNum)).append(c);
            } else if (c == ':') {
                jsonFormat.append(c).append(" ");
            } else if (c == ',' && i + 1 < length && jsonString.charAt(i + 1) == '"') {
                jsonFormat.append(c).append("\n").append(getSpaceOrTab(tabNum));
            } else {
                jsonFormat.append(c);
            }
        }
        return jsonFormat.toString();
    }

    private static boolean isTab = true;

    // 是空格还是tab
    private static String getSpaceOrTab(int tabNum) {
        StringBuilder sbTab = new StringBuilder();
        for (int i = 0; i < tabNum; i++) {
            if (isTab) {
                sbTab.append('\t');
            } else {
                sbTab.append("    ");
            }
        }
        return sbTab.toString();
    }

}
