2 Minutes To Code (β Version)

JSON and gson api - 2 minute tutorial

PrettyPrint JSON : How to convert java object to json notation with indentation

In the earlier examples, when we converted java objects to json notation, the json form was not formatted. let's see hpw to get a human-friendly json form which has proper indentations.

First of all, you need to get a com.google.gson.Gson object from a com.google.gson.GsonBuilder object with "pretty printing" turned on as show in line no. 10 below. Then just just the toJson(Object) method ( line no. 12 ) to get the formatted json form.
package com.techfundaes.gsonBag;

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

public class PrettyPrint
	public static void main(String[] args)
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		CollectionsBag collectionsBag = new CollectionsBag();
		String text = gson.toJson(collectionsBag);
If you run the above code, the json notation of com.techfundaes.gsonBag.CollectionsBag object will be printed as shown in the image below.