12

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

4 Answers 4

17

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);
Sign up to request clarification or add additional context in comments.

1 Comment

People using newer versions of Jackson, check @H Mirza's answer.
13

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);

Comments

7

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

Comments

3

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 :)

1 Comment

It only misses to skip the {,},[,] and comma in the values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.