JSON Beautifier Library for Java

后端 未结 4 1189
栀梦
栀梦 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:37

    With Jackson 2.6.1

    String beautify(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Object obj = mapper.readValue(json, Object.class);
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
    }
    

    pom.xml:

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.6.1</version>
        </dependency>
    
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.1</version>
        </dependency>
    

    Convert JSON String to Pretty Print JSON output using Jackson

    0 讨论(0)
  • 2021-02-19 22:39

    Assuming you're starting out with an existing JSON string, then Jackson can do this for you:

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
    
    String originalJson = ...
    JsonNode tree = objectMapper .readTree(originalJson);
    String formattedJson = objectMapper.writeValueAsString(tree);
    
    0 讨论(0)
  • 2021-02-19 22:50

    Update to previous answer by skaffman, with newer versions of Jackson (2+, I think). The second line of code is now:

    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
提交回复
热议问题