1. 程式人生 > >JSON字串格式化工具類-java

JSON字串格式化工具類-java


/**
 *
 * 格式化核心邏輯來源於JSON格式化 @link {http://www.bejson.com/}
 * @author joker.yyc
 */
public class JsonFormatUtils {

    /**
     * 對json字串進行格式化
     * @param content 要格式化的json字串
     * @param indent 是否進行縮排(false時壓縮為一行)
     * @param colonWithSpace key冒號後是否加入空格
     * @return
     */
    public static String toFormat
(String content, boolean indent, boolean colonWithSpace) { if (content == null) return null; StringBuilder sb = new StringBuilder(); int count = 0; boolean inString = false; String tab = "\t"; for (int i = 0; i < content.length(); i ++) { char
ch = content.charAt(i); switch (ch) { case '{': case '[': sb.append(ch); if (!inString) { if (indent) { sb.append("\n"); count ++; for
(int j = 0; j < count; j ++) { sb.append(tab); } } } break; case '\uFEFF': //非法字元 if (inString) sb.append(ch); break; case '}': case ']': if (!inString) { if (indent) { count --; sb.append("\n"); for (int j = 0; j < count; j ++) { sb.append(tab); } } sb.append(ch); } else { sb.append(ch); } break; case ',': sb.append(ch); if (!inString) { if (indent) { sb.append("\n"); for (int j = 0; j < count; j ++) { sb.append(tab); } } else { if (colonWithSpace) { sb.append(' '); } } } break; case ':': sb.append(ch); if (!inString) { if (colonWithSpace) { //key名稱冒號後加空格 sb.append(' '); } } break; case ' ': case '\n': case '\t': if (inString) { sb.append(ch); } break; case '"': if (i > 0 && content.charAt(i - 1) != '\\') { inString = !inString; } sb.append(ch); break; default: sb.append(ch); break; } } return sb.toString(); } public static void main(String[] args) { String str = "{\"name\": \"張 三 \", \"remark\": \",: {}[]啦啦啦\", \"data\": [\"1\", \"2\"]}"; System.out.println(toFormat(str, false, true)); System.out.println(toFormat(str, false, false)); System.out.println(toFormat(str, true, false)); System.out.println(toFormat(str, true, true)); } }

main方法執行結果如下

{"name": "張 三 ", "remark": ",: {}[]啦啦啦", "data": ["1", "2"]}
{"name":"張 三 ","remark":",: {}[]啦啦啦","data":["1","2"]}
{
    "name":"張 三 ",
    "remark":",: {}[]啦啦啦",
    "data":[
        "1",
        "2"
    ]
}
{
    "name": "張 三 ",
    "remark": ",: {}[]啦啦啦",
    "data": [
        "1",
        "2"
    ]
}