2 Minutes To Code (β Version)

JSON and gson api - 2 minute tutorial

Class with primitives : 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.PrimitivesBag whose source code is given in the artefacts section.
package com.techfundaes.gsonBag;

	import com.google.gson.Gson;

	public class JSONToPrimitivesBag
		public static void main(String[] args)
			Gson gson = new Gson();
			PrimitivesBag primitivesBag = new PrimitivesBag();
			String text = gson.toJson(primitivesBag);
			PrimitivesBag recreated = gson.fromJson(text, PrimitivesBag.class);

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

Notice that the String field "dept" of the PrimitivesBag 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 PrimitivesBag to textual json notation is discussed earlier.