This quick tutorial is going to how to get JSON pretty print output with Gson and Jackson.
1. Get JSON Pretty Print Output with Gson
To get JSON pretty print output with Gson, we just need to set the prettyPrinting property of the Gson instance with true value, for example:
1 2 3 4 5 6 7 8 9 10 11 12 |
@Test public void convertObjectToJson() { Book wonderBook = new Book(1000L, "Wonder", "R. J. Palacio"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(wonderBook); System.out.print(json); } |
On the above example, the gson instance was created from a GsonBuilder on which we enable JSON pretty print output by calling the setPrettyPrinting method.
Running the test will output JSON that fits in a page for pretty printing as follows:
1 2 3 4 5 |
{ "id": 1000, "name": "Wonder", "author": "R. J. Palacio" } |
2. Get JSON Pretty Print Output with Jackson
To get JSON pretty print output with Jackson, we will need to call the writerWithDefaultPrettyPrinter of the ObjectMapper class which will construct the ObjectWriter that will serialize objects using the default pretty printer for indentation, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Book eoAlBook = new Book(1004L, "The End of Alzheimer","Dale Bredesen"); try { ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(eoAlBook); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } |
The output will be:
1 2 3 4 5 |
{ "id" : 1004, "name" : "The End of Alzheimer", "author" : "Dale Bredesen" } |
3. References
Below are other related tutorials:
Ignore or Exclude Field in Gson
Ignore Unknown Properties or New Fields in Jackson