How to prettify a JSON in java?

I'm using ObjectMapper from Jackson, how can I convert an object into a pretty json?

Solution

You can do it by enabling INDENT_OUTPUT feature. This is a good option if you want to enable pretty print for all strings generated with the object mapper

ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
String prettyJson = objectMapper.writeValueAsString(object);

In alternative you can use the object mapper default pretty printer, in case you want to use the same object mapper for non-pretty jsons as well

ObjectMapper objectMapper = new ObjectMapper();
String prettyJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
Alternative #1

If you want to pretty-print JSON in a Spring Boot REST API response, you can configure the ObjectMapper globally so all your API responses are pretty-printed (useful for debugging or development environments):

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
    }
}

Or, if you only want pretty-printing in certain profiles:

# application-dev.yaml
spring:
  jackson:
    serialization:
      indent_output: true

This way, you don't have to manually call the pretty printer in every controller.

Alternative #2

If you're working with large or complex objects and want more control over the output, you can use a custom pretty printer:

ObjectMapper objectMapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(DefaultPrettyPrinter.FixedSpaceIndenter.instance);
String prettyJson = objectMapper.writer(printer).writeValueAsString(object);

You can also implement your own PrettyPrinter for custom formatting:

public class MyCustomPrettyPrinter extends DefaultPrettyPrinter {
    // Override methods for custom formatting
}

This is useful for aligning with specific formatting requirements or for log output.

Alternative #3

If you want to pretty-print JSON outside of Java (for example, in the command line or in scripts), you can use tools like jq or Python:

Using jq:

echo '{"foo": "bar", "baz": 123}' | jq .

Using Python:

echo '{"foo": "bar", "baz": 123}' | python -m json.tool

This is handy for quickly formatting JSON output from logs or API responses without changing your Java code.

Last modified: March 8, 2025
Stay in the loop
Subscribe to our newsletter to get the latest articles delivered to your inbox