Gson – GsonBuilder Configuration Examples

Lokesh Gupta

For simple usecases, using 'Gson gson = new Gson();' is enough with its standard configurations. But if you plan 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()

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 format JSON output.

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

2. FieldNamingPolicy

FieldNamingPolicy enum provides a 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.

Please note that any of the below naming conventions do 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 a different pattern for example purpose so that we can understand how each naming policy transforms different names under a 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. IDENTITY

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

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

2.2. LOWER_CASE_WITH_DASHES

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

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

2.3. LOWER_CASE_WITH_DOTS

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

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

2.4. LOWER_CASE_WITH_UNDERSCORES

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

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

2.5. 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. 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()

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.

The same rules are applied to shouldSkipField(attribute) method.

In the below example, Gson will be excluded the member field annotated 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 the comments.

Happy Learning !!

Comments

Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
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

Dark Mode

Dark Mode