Gson – GsonBuilder Configuration Examples

For simple usecases, using 'Gson gson = new Gson();' is enough with its standard configurations. But if you are planning to customize the behavior of Gson, you can use GsonBuilder to create a new Gson instance with your customized configuration.

The GsonBuilder class offers a .create() method which returns a Gson instance.

Gson gson = new GsonBuilder().create(); 

1. GsonBuilder.setPrettyPrinting() – Pretty print JSON

By default Gson will create minified JSON strings. This is important to reduce the amount of data being transferred over the network.

But this minified JSON is not helpful for developers while developing/debugging the application. Use pretty printing to formatted JSON output.

Gson gson = new GsonBuilder()
		.setPrettyPrinting()
		.create(); 

2. FieldNamingPolicy

FieldNamingPolicy enum provides few standard naming conventions for JSON field names during serialization. It helps the Gson instance to properly translate Java field names into the desired JSON field names.

Note : Please note that any of below naming convention does not affect the fields annotated with @SerializedName.

The following naming options are available. We will be verifying the names generated using each policy for User class. We have added field names in different pattern for example purpose so that we can understand how each naming policy transform different names under different policy.

public class User 
{
	private long id;
	private String first_Name;
	private String lastName;
	private String _email;
}
User user = new User(1, "Lokesh", "Gupta", "admin@howtodoinjava.com");
		
Gson gson = new GsonBuilder()
				.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
				.setPrettyPrinting().create(); 

System.out.println(gson.toJson(user));

2.1. FieldNamingPolicy.IDENTITY

Using this naming policy with Gson will ensure that the field name is unchanged. This is default behavior.

{
  "id": 1,
  "first_Name": "Lokesh",
  "lastName": "Gupta",
  "_email": "admin@howtodoinjava.com"
}

2.2. FieldNamingPolicy.LOWER_CASE_WITH_DASHES

Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by a dash (-).

{
  "id": 1,
  "first_-name": "Lokesh",
  "last-name": "Gupta",
  "_email": "admin@howtodoinjava.com"
}

2.3. FieldNamingPolicy.LOWER_CASE_WITH_DOTS

Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by a dot (.).

{
  "id": 1,
  "first_.name": "Lokesh",
  "last.name": "Gupta",
  "_email": "admin@howtodoinjava.com"
}

2.4. FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES

Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by an underscore (_).

{
  "id": 1,
  "first__name": "Lokesh",
  "last_name": "Gupta",
  "_email": "admin@howtodoinjava.com"
}

2.5. FieldNamingPolicy.UPPER_CAMEL_CASE

Gson will ensure that the first “letter” of the Java field name is capitalized when serialized to its JSON form.

{
  "Id": 1,
  "First_Name": "Lokesh",
  "LastName": "Gupta",
  "_Email": "admin@howtodoinjava.com"
}

2.6. FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES

Gson will ensure that the first “letter” of the Java field name is capitalized when serialized to its JSON form and the words will be separated by a space.

{
  "Id": 1,
  "First_ Name": "Lokesh",
  "Last Name": "Gupta",
  "_Email": "admin@howtodoinjava.com"
}

3. GsonBuilder.serializeNulls() – Serialization of null Values

By default, Gson ignores null properties during serialization. But, sometimes we want to serialize fields with null value so that it must appear in JSON. Use serializeNulls() method for this purpose.

Employee employeeObj = new Employee(1, "Lokesh", "Gupta", null);
				
Gson gson = new GsonBuilder()
		.serializeNulls()
		.setPrettyPrinting().create(); 

System.out.println(gson.toJson(employeeObj));

Program output.

{
  "id": 1,
  "firstName": "Lokesh",
  "lastName": "Gupta",
  "emailId": null
}

4. GsonBuilder.setExclusionStrategies()

ExclusionStrategy is used to decide whether or not a field or top-level class should be serialized or deserialized as part of the JSON output/input.

For serialization, if the shouldSkipClass(Class) method returns true then that class or field type will not be part of the JSON output.

For deserialization, if shouldSkipClass(Class) returns true, then it will not be set as part of the Java object structure.

Same rules are applied on shouldSkipField(attribute) method.

In below example, Gson will be excluded member field annotaed with @NPI annotation and all Account class instances from serialization and deserialization.

Gson gson = new GsonBuilder()
	.setExclusionStrategies(new ExclusionStrategy() {
		@Override
		public boolean shouldSkipField(FieldAttributes f) {
			return f.getAnnotation(NPI.class) != null;
		}

		@Override
		public boolean shouldSkipClass(Class<?> clazz) {
			return clazz.getAnnotation(Account.class) != null;
		}
	})
	.setPrettyPrinting()
	.create(); 

5. GsonBuilder.setLenient() – Relaxed JSON syntax rules

During deserialization, Gson uses a JsonReader class which is not lenient. It means it only accepts compliant JSON input. If the JSON violates one of the structure rules, it will throw MalformedJsonException.

If we set lenient to true, it’ll swallow certain violations and try it’s best to read even a poorly formatted JSON.

Gson gson = new GsonBuilder()
		.setLenient()
		.setPrettyPrinting().create(); 

These are some most commonly used GsonBuilder configuration methods and their uses. Drop me your questions in comments.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial