Pretty print JSON response in Spring Boot Pretty print JSON response in Spring Boot

In this quick article, we’ll learn how to pretty print JSON response in Spring Boot web application using Jackson property.

Overview

When you create a @RestController in a Spring Boot application to define RESTFul API endpoints then HttpMessageConverters is used to convert Java Object to JSON or XML in order to render the response.

Spring Boot by default render JSON response using MappingJackson2HttpMessageConverter which use Jackson JSON ObjectMapper library.

Rendered JSON response is not pretty print by default but you can enable it with just one property change.

Example

  1. We first 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")		     
    		});
    	}
    }
    
  2. We see that default JSON Response is not pretty print:-

    JSON response

  3. Now we 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
  4. We restart the application and see that now JSON response is pretty print:-

    JSON response


Relax Binding

Please note that spring boot configuration support Relaxed Binding that means properties can be in uppercase or lowercase, both are valid.

spring.jackson.serialization.INDENT_OUTPUT = true

is same as

spring.jackson.serialization.indent_output = true

That’s it for now.

Download the source code for more Jackson related config examples from github/springboot-api