Jackson - Comment activer la sortie JSON jolie impression
Dans Jackson, nous pouvons utiliserwriterWithDefaultPrettyPrinter()
pour afficher la sortie JSON.
Testé avec Jackson 2.9.8
1. Pretty Print JSON
1.1 By default, Jackson print in compact format:
ObjectMapper mapper = new ObjectMapper(); Staff staff = createStaff(); String json = mapper.writeValueAsString(staff); System.out.println(json);
Sortie
{"name":"example","age":38,"skills":["java","python","node","kotlin"]}
1.2 To enable pretty print on demand.
ObjectMapper mapper = new ObjectMapper(); Staff staff = createStaff(); // pretty print String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff); System.out.println(json);
Sortie
{ "name" : "example", "age" : 38, "skills" : [ "java", "python", "node", "kotlin" ] }
1.3 To enable pretty print globally.
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; // pretty print ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); Staff staff = createStaff(); String json = mapper.writeValueAsString(staff); System.out.println(json);
Sortie
{ "name" : "example", "age" : 38, "skills" : [ "java", "python", "node", "kotlin" ] }
Note
Pour afficher la sortie JSON jolie impression sur une page HTML, l'encapsule avec les balisespre
.<pre>${pretty-print-json-output}</pre>
Note – 12/12/2013
L'article est mis à jour pour utiliserwriterWithDefaultPrettyPrinter()
, l'anciendefaultPrettyPrintingWriter()
est obsolète.