Configuring Gson object

In this post under GSON, I will explain how to configure the Gson instance.

In all my previous post under GSON, I used to create a Gson instance by using the below code snippet.


Gson gson = new Gson();

With this instance we used convert java object to and from JSON format.

This instance comes up with default configurations.

Configurations such as pretty printing, html setting etc are set to default values and we cannot change them once the Gson instance is created.

The solution is to use GsonBuilder class. GsonBuilder class allows us to configure the Gson instance in the way we want.

Below is example of how to use GsonBuilder class.

Main Code


1  import java.util.Date;
2  
3  import com.google.gson.Gson;
4  import com.google.gson.GsonBuilder;
5  
6  public class GsonDemo5 {
7   public static void main(String[] args) {
8       GsonBuilder gsonBuilder = new GsonBuilder();
9       Gson gson = gsonBuilder.setPrettyPrinting().create();
10      Student student = new Student();
11      student.setId(1);
12      student.setName("name1");
13      student.setRollnum(100);
14      student.setDate(new Date());
15      String result = gson.toJson(student);
16      System.out.println(result);
17  }
18 }

In the above code we are enabling the pretty printing feature of Gson. By default it is disabled.

At line 8, we create an instance of GsonBuilder named “gsonBuilder”.

At line 9, we are enabling the pretty printing feature by calling “setPrettyPrinting” method on gsonBuilder and then we call “create” method to create a Gson instance with pretty printing enabled.

The output of the above code will be

Output

{
“id”: 1,
“name”: “name1”,
“rollnum”: 100,
“date”: “Aug 24, 2019 12:47:45 PM”
}


Check these products on Amazon
Advertisements

Leave a Reply