Json string not formatted in browser but formatted in console

I am trying to output object serialized to json like this

@GetMapping("/person")
public String getPerson() throws JsonProcessingException {
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    System.out.println(mapper.writeValueAsString(person)); //just for debug
    return mapper.writeValueAsString(person);
}

I get what I wish in console:

{
  "name" : "person",
  "age" : 29,
  "listSkills" : [ "s1", "s2", "s3" ],
  "id" : 1,
  "hashCode" : 2145420209
} 

but in browser it is printed in one line and just gets different font

{ "name" : "person", "age" : 29, "listSkills" : [ "s1", "s2", "s3" ], "id" : 1, "hashCode" : 2145420209 }


Solution 1:

Problems

  1. You expect browser to have the same font(and colors) as console!? (Your expectations "base on wrong assumptions"/you must care)
  2. You don't use @[Rest]Controller as intended/documented.
  3. Obviously ResponseBody<String> (which you in fact return) doesn't behave as expected regarding white space.

Solution

  1. Spring-boot-starter-web [x]

  2. application.properties:

    spring.jackson.serialization.indent_output=true
    
  3. Impl:

    • Person:
      package com.example.webtest;
      import java.time.LocalDate;
      
      public class Person {
         private String name;
         private LocalDate date;
         // default constructor (implicit)
         // getters, setters:
         public String getName() {
           return name;
         }
         public Person setName(String name) {
           this.name = name;
           return this; // fluent api (not mandatory...)
         }
         public LocalDate getDate() {
           return date;
         }
         public Person setDate(LocalDate date) {
           this.date = date;
           return this;
         }
      }
      
    • Application + Controller:
      package com.example.webtest;
      
      import java.time.LocalDate;
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.RestController;
      
      @SpringBootApplication
      public class WebTestApplication {
      
         public static void main(String[] args) {
           SpringApplication.run(WebTestApplication.class, args);
         }
      
         @RestController
         static class SomeController {
      
           @GetMapping("/hello")
           public Person hello() { // Person! not String ;)
             return new Person().setName("Joe").setDate(LocalDate.now());
           }
         }
      }
      
  4. Test (spring-boot:run,..browser) at http://localhost:8080/hello:

    enter image description here

Key points

  • Using spring-boot "jacksonObjectMapper" (auto & properties config).
  • Returning the desired type and not a String.