728x90 AdSpace

Sunday, 6 October 2013

JSON Pretty Print using GSON

In this tutorial we are going to see how to Create Pretty Print JSON String using GSON.
1. Create project called JSONExample.
2. Create package called com.javatutorialscorner.gson 
3. Create java class called GsonPojo under com.javatutorialscorner.gson.

package com.javatutorialscorner.gson;

import java.util.List;

public class GsonPojo {

private int var1 = 10;
private String var2;
private List<String> list;

public int getVar1() {
return var1;

public void setVar1(int var1) {
this.var1 = var1;

public String getVar2() {
return var2;

public void setVar2(String var2) {
this.var2 = var2;

public List<String> getList() {
return list;

public void setList(List<String> list) {
this.list = list;


4. Now Create java class called GSONPrettyPrintExample under com.javatutorialscorner.gson.


The setPrettyPrinting()  method available in  GsonBuilder class used to create Pretty Print JSON.

package com.javatutorialscorner.gson;

import java.util.ArrayList;
import java.util.List;

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

public class GSONPrettyPrintExample {

* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub

List<String> list = new ArrayList<String>();
list.add("Struts 1.x");
list.add("Struts 2.x");

GsonPojo pojo = new GsonPojo();
pojo.setVar2("Java Tutorials Corner");
Gson gson = new Gson();
String json = gson.toJson(pojo);

System.out.println("Normal JSON : " + json);

Gson gson2 = new GsonBuilder().setPrettyPrinting().create();

String json2 = gson2.toJson(pojo);

System.out.println("JSON Pretty Print : " + json2);



Now run the program see the following output in console.

Normal JSON : {"var1":10,"var2":"Java Tutorials Corner","list":["Java","Sevlet","JSP","JSF","Struts 1.x","Struts 2.x","Tiles","Spring","Hibernate"]}
JSON Pretty Print : {
"var1": 10,
"var2": "Java Tutorials Corner",
"list": [
"Struts 1.x",
"Struts 2.x",
Annamalai Thangaraj

Annamalai is working as Technical Lead in Leading Telecom company with 5+ years experience in Identity and Access Management , Telecom and Networks, BigData, Java, Spring, Struts, Hibernate, AngularJS, and Enterprise Web Application Development.

Website: Java Tutorials Corner

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments


Post a Comment

Item Reviewed: JSON Pretty Print using GSON Rating: 5 Reviewed By: Annamalai Thangaraj