2 Minutes To Code (β Version)

JSON and gson api - 2 minute tutorial

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

		import com.google.gson.Gson;

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

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

Notice that the SimpleDateFormat field "sdf" of the ObjectsBag 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 ObjectsBag to textual json notation is discussed earlier.