Aug 23, 2015

How to pretty print JSON using Gson and Jackson

JSON is widely used in web development as data exchange format because of its light weight nature.By default JSON is plain string however JSON looks scary if it is not formatted and in may situation formatted JSON is need for debugging.Here we will see how to format or how to enable pretty printing of JSON in java. If you are using Gson and Jackson then it is very easy to generate pretty print of JSON.

JSON Pretty printing using Gson:- 

Gson has GsonBuilder has instance variable prettyPrinting(Boolean), while creating instance of GsonBuilder using create() method, if prettyPrinting is set true(using setPrettyPrinting() method ) then pretty printing will be enabled and JSON generated will be formatted. Download Gson jar from here and create a java file with following code lines.
Hide code lines
package com.GsonSampleProject.model;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JSONPrettyPrintUsingGson {
  public static void main(String[] args) {
    Map<String, Object> map = new LinkedHashMap<>();
    List<String> skills = new LinkedList<>(
        Arrays.asList("java""python",
        "hadoop"));
    map.put("Name""nikhil");
    map.put("Designation""SSE");
    map.put("skills", skills);
    // Create() method returns an instance of Gson,
    // call toJson() method and prints formatted JSON.
    Gson gObj = new GsonBuilder().setPrettyPrinting().create();
    System.out.println(gObj.toJson(map));
   
  }
}
Here we have created a map(object of JSON) and added a list (array of JSON) as part of it. Whne we execute JSON is pretty printed. Similarly , we can have any POJO(Plain old java object) in-place of map and outcome is pretty printed.   

JSON Pretty printing using Jackson:- 

Download jackson-all-1.9.0.jar. Create a java class and use following code lines.
Hide code lines
package com.GsonSampleProject.model;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.SerializationConfig;

public class JSONFormattedWithJackson {
  public static void main(String[] args) {
    Map<String, Object> map = new LinkedHashMap<>();
    List<String> skills = new LinkedList<>(Arrays.asList("java""python",
        "hadoop"));
    map.put("Name""nikhil");
    map.put("Designation""SSE");
    map.put("skills", skills);
    String jsonString = "[{\"Name\":\"Nikhil\",\"skills\":[\"java\","
        "\"python\",\"Hadoop\"],\"Address\":\"Hyderabd\"},"
        "{\"Name\":\"Ranjan\",\"skills\":[\"java\","
        "\"python\",\"NoSQL\"],\"Address\":\"Hyderabd\"}]";
    ObjectMapper mapper = new ObjectMapper();
    try {
      System.out.println("==========Option 1===========");
      // 1. String to Formatted JSON conversion
      Object jsonObjet = mapper.readValue(jsonString, Object.class);
      // for Jackson 1.x only use
      ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
      // for jackson 2.x use following
      // ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
      String indentedResult1 = writer.writeValueAsString(jsonObjet);
      System.out.println(indentedResult1);
      //2. Object to formatted JSON conversion
      String indentedResult2 = writer.writeValueAsString(map);
      System.out.println(indentedResult2);
      
      System.out.println("==========Option 2===========");
      // Object to Formatted JSON conversion
      mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
      System.out.println(mapper.writeValueAsString(map));
    catch (JsonParseException e) {
      e.printStackTrace();
    catch (JsonMappingException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    }

  }
}
Here we have multiple option to convert String/Object into pretty print format. In option 1, we  created mapper instance of ObjectMapper and mapper instance have readValue method that read input(FIle, InputStream,String or Object) and with writeValueAsString() method it displays formatted output.Please note difference mentioned for 1.x and 2.x. Do not use defaultPrettyPrintingWriter() ,it has been deprecated instead prefer to use Option 2. In second option, we enable properties in mapper for "INDENT_OUTPUT", so by default if object is printed it will be pretty printed.

Read also:
How to convert JSON to Object and Object to JSON using Google Gson.
Location: Hyderabad, Telangana, India