2 Minutes To Code (β Version)

JSON and gson api - 2 minute tutorial

Class with collections : How to convert java object to json notation

The example below shows how to convert a java object having collection objects as fields to json notation using gson api.

For converting, you need to get a com.google.gson.Gson object using its default constructor (line no. 9). Then, call the method toJson(Object) of the Gson object to get the json form as String (line no. 11).

The java object converted to json notation is an an instance of com.techfundaes.gsonBag.CollectionsBag whose source code is given in the artefacts section.
package com.techfundaes.gsonBag;

		import com.google.gson.Gson;

		public class JSONForCollectionsBag
		{
			public static void main(String[] args)
			{
				Gson gson = new Gson();
				CollectionsBag collectionsBag = new CollectionsBag();
				String text = gson.toJson(collectionsBag);
				
				System.out.println(text);
			}
		}

	
\
If you run the above code, the json notation of CollectionsBag object will be printed as shown in the image below.

Notice that the TreeMap field "gameAuthorMap" of the CollectionsBag object is absent from the json notation. This is because its value was null. Later, we will see how to retain even null fields in json notation.
The reverse process, that is coverting textual json notation to java object of class CollectionsBag is discussed later.