Home > Software Development > How to Pretty Print JSON with Gson and Jackson

How to Pretty Print JSON with Gson and Jackson

In my last article, I compared two leading JSON APIs in Java: Jackson and Gson. If you have tried the samples there, you may have noticed that the two samples print the JSON string into one line. While it’s pretty efficient for machine, it may not easy for human consumption when the Json string is long. Sometimes I have to copy a long Json string into an editor to find out what are there.

Pretty Print a Java Object into Json

Time to learn how to "Google" and manage your VMware and clouds in a fast and secure


It’s actually quite easy to pretty print a JSON string. The following sample shows how to pretty print a Java object with both Gson and Jackson APIs. In real world, you don’t need to use both APIs. So feel free to copy and paste the relavant part of the code. Same for the Maven dependencies. Most likely you don’t need both dependencies in your project.

package org.doublecloud.json.demo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class PrettyJsonPrint
  public static void main(String[] args) throws Exception
    Book book = new Book();
    book.author = "Steve Jin";
    book.title = "VMware vSphere and VI SDK";
    // using Gson API
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String bookJson = gson.toJson(book);
    System.out.println("pretty print json using Gson:\n" + bookJson);
    // using Jackson API
    ObjectMapper mapper = new ObjectMapper();
    bookJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(book);
    System.out.println("pretty print json using Jackson:\n" + bookJson);
class Book
  public String author;
  public String title;

In Maven is used, the following dependencies are needed:


Convert Json String into Pretty Format

Ideally there can be direct conversion from free format Json to pretty format. I haven’t found such a direct API for the conversion. An indirect way to achieve this is quite easy too: first parse the free form Json string to a Java object and then pretty print the Java object. Please check out my previous article for the details.

Note that because the purpose of the parsing is simply for later printing. It’s not necessary to parse the String to the exact type, which may take more effort and time. Just parse the string to Java Object should be good enough for later printing.

Categories: Software Development Tags: ,
  1. No comments yet.
  1. No trackbacks yet.