Reputation: 7
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 }
Upvotes: 0
Views: 1226
Reputation: 13281
@[Rest]Controller
as intended/documented.ResponseBody<String>
(which you in fact return) doesn't behave as expected regarding white space.application.properties:
spring.jackson.serialization.indent_output=true
Impl:
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;
}
}
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());
}
}
}
Test (spring-boot:run,..browser) at http://localhost:8080/hello
:
Upvotes: 1
Reputation: 300
In Spring boot, the GET method will produce result with content type of application/json
by default.
If you want a formatted string in browsers, set produces to text/plain
, aka
@GetMapping(value = "/person", produces = MediaType.TEXT_PLAIN_VALUE)
Upvotes: 0
Reputation: 2794
You can install a json formatter for your browser e.g. for Chrome this one is quite popular: JSON Formatter or you can find a similar one for your browser of choice.
Usually they come with great features such as sintax highlighting, clickable urls, toggles and some more.
Upvotes: 0