2 Minutes To Code (β Version)

JSON and gson api - 2 minute tutorial

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

The example below shows how to convert json notation to the corresponding java object 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 fromJson(String, Class) of the Gson object to get the object instance (line no. 13).

The java object recreated from 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 JSONToCollectionsBag
			public static void main(String[] args)
				Gson gson = new Gson();
				CollectionsBag collectionsBag = new CollectionsBag();
				String text = gson.toJson(collectionsBag);
				CollectionsBag recreated = gson.fromJson(text, CollectionsBag.class);

If you run the above code, the java object CollectionsBag will be printed as shown in the image below.

Notice that the TreeMap field "gameAuthorMap" of the CollectionsBag object which was absent from the json notation is initialzed as null in the recreated object.
The reverse process, that is coverting java object of CollectionsBag to textual json notation is discussed earlier.