2 Minutes To Code (β Version)

JSON and gson api - 2 minute tutorial

Class with custom objects : How to convert java object to json notation

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

		import com.google.gson.Gson;

		public class JSONForObjectsBag
			public static void main(String[] args)
				Gson gson = new Gson();
				ObjectsBag objectsBag = new ObjectsBag();
				String text = gson.toJson(objectsBag);

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

Notice that the SimpleDateFormat field "sdf" of the ObjectsBag 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 ObjectsBag is discussed later.