2 Minutes To Code (β Version)

JSON and gson api - 2 minute tutorial

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

The example below shows how to convert a java object having only primitive 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.PrimitivesBag whose source code is given in the artefacts section.
package com.techfundaes.gsonBag;

		import com.google.gson.Gson;

		public class JSONForPrimitivesBag
			public static void main(String[] args)
				Gson gson = new Gson();
				PrimitivesBag primitivesBag = new PrimitivesBag();
				String text = gson.toJson(primitivesBag);
If you run the above code, the json notation of PrimitivesBag object will be printed as shown in the image below.

Notice that the String field "dept" of the PrimitivesBag 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 PrimitivesBag is discussed later.