Aug 22, 2015

In previous post we learned How to parse/encode-decode JSON using JSON.simple.JSON is known for its light weight data exchange format. In web centric application integrated with Object oriented infrastructure, their will be high volume of data exchange and data are sent in form of JSON over wires.So, how do we convert (serialize) object to JSON and retrieve that object to JSON(deserialize). The main agenda of this post is understand serialization and de-serialization using GSON- an open source java library for converting Java Objects into their JSON and from JSON to java Objects. Some important features of GSON:

Gson has extensive support for java generics.Gson can be used to convert complex hierarchy of connected object model into JSON and vice versa.

Gson can work with arbitrary Java objects including pre-existing objects whose source code we cannot modify.Gson can also be used to convert third party object into JSON.

Java Object to JSON using Gson

Create a java project and add download jar in class path/add dependency in pom.xml, if maven project. Create a POJO Employee.java, we will create employee list and convert it into JSON. Create a Employee.java with following code lines: Here we have two level of class hierarchy - connected object model (SalaryComponents inside Employee).

Now we will create our processing unit ,SerialDeserialUsinGson.java with following code lines. Here we have created Gson object (using default constructor with default values).We can create Gson object with various customization like changing fields name, allow serialization of nulls by passing boolean value(by default nulls are serialized). We will revisit this advanced concept later. As of now use default values of Gson class.

Let's walk thorough the above code, first we created two employee object via for loop(Scary code☺) just ignore the logic.Next we created Gson object and used toJson method of Gson class to convert employee List into JSON structure.Run above program and see the output, we will get compact JSON structure.Now uncomment last line of the code and run it again. This time outcome is formatted and prettyprint JSON is displayed on console. For more details How to pretty print JSON in java ?