GSON Example – Convert Java objects to / from JSON

GSON – Java

GSON (also known as Google Gson) is an open source Java library used to convert Java objects to (and from) JSON. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is widely used in RESTful web applications. In RESTful web services, most of the times the response needs to be sent in JSON format. Since in Java everything is dealt as an object, the developer needs to convert the Java objects into JSON format and then send it as a response. Hence it is very useful for the Java developers to learn GSON APIs.

GSON API can be found here Gson API.
GSON jar can be downloaded here Gson jar.

The GSON API provides a class, Gson which handles the conversions between Java and JSON objects.

GSON example- Java object to JSON:

Let us first create necessary POJO classes to use in our examples.

Java to JSON converter:

Output:

{
“empName”: “Emp1”,
“empId”: 1,
“empDept”: [{
“deptName”: “Physics”,
“deptId”: 1
}, {
“deptName”: “Chemistry”,
“deptId”: 2
}] }
Note: The default JSON output that is provided by Gson is a compact JSON format. So there will not be any white-space in the output JSON structure. To generate a more readable and pretty looking JSON we used setPrettyPrinting() in GsonBuilder.

Let us convert the above JSON string to Employee object.

JSON to Java object converter:

Output:

Employee name: Emp1
Employee Id: 1
Employee Dept1: Physics
Employee Dept2: Chemistry

Custom Serialization and De-serialization:

Often times we will be using custom format for certain fields like Date fields in an object. In this case when we use GSON API for serialization (Java to JSON) and deserialization (JSON to Java), we need to tell GSON to use the custom formatter.
Let us see an example program for that.
First we need to create a serializer and deserializer for java.util.Date class and need to register with GSON parser. Here we will use custom date format of MM/dd/yyyy.

GsonDateSerializer.java

GsonDateDeserializer.java

Employee.java

GsonJavaToJson.java

Output:

{
“empName”: “Emp1”,
“empId”: 1,
“dob”: “03/02/2016”
}
Let us convert the above JSON string to Employee object.

GsonJsonToJava.java

Output:

Employee name: Emp1
Employee Id: 1
Employee DOB: Wed Mar 02 00:00:00 IST 2016

Summary:

• JSON is a light weight and straight forward format.
• JSON is widely used in RESTful web services.
• GSON makes it easy to convert Java objects to / from JSON.
• For custom serialization and deserialization you need to write custom serializer and deserializer and register it in the GSON converter.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.
4 comments

Add Comment

Required fields are marked *. Your email address will not be published.