JSON Beautifier Library for Java

后端 未结 4 1162
栀梦
栀梦 2021-02-19 22:02

I want to format a string containing JSON data using Java. Does anybody know an open source library for that.

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-19 22:54

    I made a simple code can do this, you just need to create a new class call BeautifulJson and paste all of them in.

    public class BeautifulJson {
        public static String beautiful(String input) {
            int tabCount = 0;
    
            StringBuilder inputBuilder = new StringBuilder();
            char[] inputChar = input.toCharArray();
    
            for (int i = 0; i < inputChar.length; i++) {
                String charI = String.valueOf(inputChar[i]);
                if (charI.equals("}") || charI.equals("]")) {
                    tabCount--;
                    if (!String.valueOf(inputChar[i - 1]).equals("[") && !String.valueOf(inputChar[i - 1]).equals("{"))
                        inputBuilder.append(newLine(tabCount));
                }
                inputBuilder.append(charI);
    
                if (charI.equals("{") || charI.equals("[")) {
                    tabCount++;
                    if (String.valueOf(inputChar[i + 1]).equals("]") || String.valueOf(inputChar[i + 1]).equals("}"))
                        continue;
    
                    inputBuilder.append(newLine(tabCount));
                }
    
                if (charI.equals(",")) {
                    inputBuilder.append(newLine(tabCount));
                }
            }
    
            return inputBuilder.toString();
        }
    
        private static String newLine(int tabCount) {
            StringBuilder builder = new StringBuilder();
    
            builder.append("\n");
            for (int j = 0; j < tabCount; j++)
                builder.append("  ");
    
            return builder.toString();
        }
    }
    
    

    To use this:

    String beautifulJson = BeautifulJson.beautiful("JSON in string");
    

    Example:

    static String json = "{\"success\": true,\"metadata\": {\"transactionId\": 0,\"status_code\": 0},\"errors\": [{\"code\": \"string\",\"message\": \"string\"}]}";
    
    public static void main(String[] args) {
        //Original JSON
        System.out.println(json);
        //beautiful JSON
        System.out.println(beautiful(json));
    }
    

    This is my first post on stack overflow :)

提交回复
热议问题