Gson tutorial
Google GSON is JSON parser and generator for java. Google developed GSON for internal use but later open sourced. Gson is relatively easy to use, it contains multiple APIs which you can use to work with JSON. In this GSON tutorial we will go through how to use GSON to parse JSON into Java objects and serialize Java objects into JSON.
These are few topics which we will discussing in this tutorial.
- Creating a GSON object.
- Converting JSON into Java Objects.
- Generating JSON from Java Objects.
- Pretty printing.
- Custom Instance creators in GSON.
- Custom Serialization and Deserialization.
- Version support in GSON.
Create simple POJO which we will use further in our tutorial.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class Emp { private int id; private String firstName; private String lastName; public Emp() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Id : " + id); sb.append(", FirstName : " + firstName); sb.append(", Last Name : " + lastName); return sb.toString(); } } |
-
Creating a GSON object.
There are two ways to create a Gson object.
- Using new Gson()
- Creating a GsonBuilder instance and calling create() on it.
-
new Gson()
We can create Gson object simply by calling default constructor of Gson class. Similar to other class in Java we can create object of Gson.
1Gson gson = new Gson(); -
GsonBuilder.build()
Another way to create a Gson instance is to create a GsonBuilder() and call its create() method. Below is an example to create a GsonBuilder and calling create().
12GsonBuilder builder = new GsonBuilder();Gson gson = builder.create();Once object of Gson is created we can use it to parse and generate JSON.
-
Converting JSON into Java Objects.
Using the fromJson() method of Gson API we can parse JSON string into java object. Here is an example of converting JSON into Java object.
1234567String jsonString = "{'id':1, 'firstName':'Rahul','lastName':'Anand'}";Gson gson = new Gson();Emp emp = gson.fromJson(jsonString, Emp.class);System.out.println(emp);Output :Id : 1, FirstName : Rahul, Last Name : AnandThere are two parameters in fromJson() method. The first parameter is json String which we want to parse and the second parameter is Java class to parse JSON string.
-
Generating JSON from Java Objects.
Using the toJson() method of Gson API we can convert java objects into JSON string. Here is an example to generate JSON from java objects.
1234567891011Emp emp = new Emp();emp.setId(1);emp.setFirstName("Rahul");emp.setLastName("Anand");Gson gson = new Gson();String jsonString = gson.toJson(emp);System.out.println(jsonString);Output :{"id":1,"firstName":"Rahul","lastName":"Anand"}One parameter we are passing into toJson() method is the java object which we want to convert into JSON string.
You can find more examples like convert List, Map and any other object to/from json using gson in our tutorial convert object to/from json using gson.
-
Pretty printing.
Gson provide JSON output in compact format which you can see in above example is not contains any whitespace or intonation. So, the default output is not very much readable to developers. However in case we want to format the output of Gson we can use setPrettyPrinting() method of GsonBuilder class.
12345678910Gson gson = new GsonBuilder().setPrettyPrinting().create();String jsonString = gson.toJson(emp);System.out.println(jsonString);Output :{"id": 1,"firstName": "Rahul","lastName": "Anand"} -
Custom Instance creators in GSON.
While parsing JSON String to or from Java object, By default Gson try to create instance of Java class by calling default constructor. In case Java class doesn’t contain default constructor or you want to do some initial configuration while creating Java objects, you need to create and register your own instance creator.
POJO class which don’t have default constructor.
12345678910public class Address {private String addressLine1;private String addressLine2;private String city;public Address(String city) {this.city = city;}//other setter and getter methods}Instance creator class for Address.
1234567public class AddressCreator implements InstanceCreator<Address> {@Overridepublic Address createInstance(Type type) {Address address = new Address("New York");return address;}}Now test the code.
12345678910GsonBuilder gsonBuilder = new GsonBuilder();gsonBuilder.registerTypeAdapter(Address.class, new AddressCreator());Gson gson = gsonBuilder.create();String jsonString = "{'addressLine1':'line1', 'addressLine2':'line2'}";Address address = gson.fromJson(jsonString, Address.class);System.out.println(address);Output:ÄddressLine1 : line1, ÄddressLine2 : line2, city : New York -
Custom Serialization and Deserialization.
Now a days complex applications are build where different teams are collaborating with each other to make a project successful. There are some scenarios where UI team created their UI component expecting value of isActive field will be ‘Y’ or ‘N’ while as a backend developer you have created your bean for isActive field as boolean. So while converting the bean to JSON string with isActive as boolean UI team gets true or false value.To handle this kind of scenario Gson come with the concept of Custom Serialization and Deserialization.
First create a bean User with userName as string and isActive as boolean.
12345678public class User {private String userName;private boolean isActive;public User(){}//getter setter methods}Custom Serializer.
To create custom serializer in Gson you have to implement the JsonSerializer interface which looks like
12345public interface JsonSerializer<T> {public JsonElement serialize(T value, Type type,JsonSerializationContext jsonSerializationContext) {}}Here value field in method serialize means the data type of field you want to serialize.
Customer BooleanSerializer which converts true value to “Y” and false to “N”.12345678910public class BooleanSerializer implements JsonSerializer<Boolean> {@Overridepublic JsonElement serialize(Boolean bool, Type type, JsonSerializationContext arg2) {if(bool) {return new JsonPrimitive("Y");}else {return new JsonPrimitive("N");}}}Now we need to register this custom serializer class to GsonBuilder class before creating the gson instance from the gsonBuilder. Below example demonstrates this.
123456789101112131415GsonBuilder gsonBuilder = new GsonBuilder();gsonBuilder.registerTypeAdapter(Boolean.class, new BooleanSerializer());Gson gson = gsonBuilder.create();//create user beanUser user = new User();user.setUserName("rahul");user.setActive(true);//serialize user objectString jsonString = gson.toJson(user);System.out.println(jsonString);Output:{"userName":"rahul","isActive":"Y"}So, you can see we have created user object with username as “rahul” and has set as Active user with value true.In output userName is coming as rahul while isActive field populated as Y. So, our custom serializer is working.
Custom Deserializer
In Custom serializer section we have converted User class to Json String where values of isActive field replaced with Y or N. Now if we want to convert ‘{“userName”:”rahul”,”isActive”:”N”}’ JSON string back to User class which has isActive field as boolean, you have to write custom deserializer class.
To create custom serializer in Gson you have to implement the JsonDeserializer interface which looks like.12345public interface JsonDeserializer<T> {public Boolean deserialize(JsonElement jsonElement,Type type, JsonDeserializationContext jsonDeserializationContext)throws JsonParseException;}Customer BooleanDeserializer which converts “Y” to true and “N” to false.
12345678public class BooleanDeserializer implements JsonDeserializer<Boolean> {@Overridepublic Boolean deserialize(JsonElement jsonElement, Type type,JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {return jsonElement.getAsString().equals("Y")? true: false;}}Now we need to register this custom deserializer class to GsonBuilder class before creating the gson instance from the gsonBuilder. Below example demonstrates this.
123456789GsonBuilder gsonBuilder = new GsonBuilder();gsonBuilder.registerTypeAdapter(Boolean.class, new BooleanDeserializer());Gson gson = gsonBuilder.create();String jsonString = "{'userName':'rahul','isActive':'N'}";User user = gson.fromJson(jsonString, User.class);System.out.println(user.isActive());Output : false -
Version support in Gson
Gson supports version control while reading and writing Java objects. Version support is very useful when we are working in a group where lots of other applications interacting with your code and you are changing your Java bean frequently to support them. For version control in Gson you have to annotate your fields with version number then Gson includes or exclude fields based on their version number while converting JSON string to Java object and vice versa.You have to use @Since annotation in your Java classes for version support. Let modify our Emp class with @Since annotation.
123456789101112131415public class Emp {@Since(1.0)private int id;@Since(1.0)private String firstName;@Since(1.0)private String lastName;@Since(2.0)private Address address;public Emp(){}//getter setter methods}So we have annotated Id, firstName and lastName with version 1.0 while Address with version 2.0.
Now while creating Gson object you have to use GsonBuilder where you can set version control to create gson object as below example.123GsonBuilder gsonBuilder = new GsonBuilder();gsonBuilder.setVersion(1.0);Gson gson = gsonBuilder.create();Gson instance created from GsonBuilder which is created with version number 1.0 will include id, fisrtName and lastName as these fields are annotated with @Since(1.0). It excludes address fields as it is annotated with @Since(2.0).
Let’s create object of Emp class and see generated json String.123456789101112Emp emp = new Emp();emp.setId(1);emp.setFirstName("Rahul");emp.setLastName("Anand");Address address = new Address("line1", "line2", "London");emp.setAddress(address);String jsonString = gson.toJson(emp);System.out.println(jsonString);Output:{"id":1,"firstName":"Rahul","lastName":"Anand"}As you can see in the above code we have created object of Address class and set it to emp object. In output we have JSON String which contains id, firstName and lastName fields. So, while converting Java object to JSON string Gson exclude address field as it is annotated with @Since(2.0).
Let use the same gson object to convert JSON string with address field to Java object.
123456String jsonString = "{'id':1, 'firstName':'Rahul','lastName':'Anand', 'address': {'line1': 'address1', 'line2': 'address2', 'city': 'London'}}";Emp emp = gson.fromJson(jsonString, Emp.class);System.out.println(emp);Output:Id : 1, FirstName : Rahul, Last Name : Anand, Address : nullIn output you can see id, firstName and lastName are populated while Address is not. So Gson supports version control while converting Java Object to JSON string and vice versa.
Stay tuned for more examples and tutorial related with Gson.