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

Bothered by SLOW Web UI to manage vSphere? Want to manage ALL your VMware vCenters, AWS, Azure, Openstack, container behind a SINGLE pane of glass? Want to search, analyze, report, visualize VMs, hosts, networks, datastores, events as easily as Google the Web? Find out more about vSearch 3.0: the search engine for all your private and public clouds.

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();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    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:

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.2.3</version>
      <type>jar</type>
    </dependency>
 
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.0</version>
      <type>jar</type>
    </dependency>

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.

This entry was posted in Software Development and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  • NEED HELP?


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.