Pretty print JSON response in spring boot Pretty print JSON response in spring boot

When you create a Spring @RestController in a Spring Boot application to define API endpoints then it renders JSON response by default if jackson2 is in classpath.

JSON responses are not pretty print by default but you can enable it with just one property change.

Let’s create a @RestController class.

@RequestMapping("/posts")
public class PostController {

	@GetMapping
	public List<Post> getAllPosts() {
		return Arrays.asList(new Post[] {
		     new Post(1, "post title 1", "post body 1"),
		     new Post(2, "post title 2", "post body 2"),
		     new Post(3, "post title 3", "post body 3")		     
		});
	}
}

Look at default JSON Response,

JSON response

We see that by default JSON response is not pretty print. Just add following property depending upon you are using .properties or .yml file

application.properties
spring.jackson.serialization.indent_output = true
application.yml
spring:
  jackson:
    serialization:
      indent_output: true


Restart your application after adding property. You will now see pretty print JSON response.

JSON response