Gson With Spring Boot Configuration and Customization

Gson With Spring Boot

In this article of Spring Boot, We will learn how to configure Gson with Spring Boot framework.

By Default, Spring Boot uses Jackson for Serializing and Deserializing of request and response objects for REST APIs.

If you want to use GSON instead of Jackson as your json mapper then follow the below article explained with example.

Let’s get started :

What is Gson ?

Before understanding the Gson configurations with Spring Boot. Let’s take a look at Gson Introduction :

Gson is a library provided by Google. Gson is an open source library. It is a simple Java-based library which is used for serializing and deserializing of Objects.

It serialize the Java objects to JSON and deserialize the JSON to Java Objects.

Gson With Spring Boot.

Gson features and advantages :

  • Standardized − Gson is a standardized library managed and developed by Google.
  • Optimized − Gson library is highly optimized.
  • Support Generics − Generics is supported by Gson library.
  • Efficient − Gson is a fast, reliable and efficient extension to the Java standard library.
  • Supports complex inner classes − Gson supports the very complex objects with deep inheritance hierarchies.

Adding Gson Maven Dependency

Add the below Gson dependency in your project’s pom.xml file:

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.8.5</version>
</dependency>

Gson Auto-Configuration

As we add the Gson dependency in our Project, Spring Boot automatically detects the Gson dependency presence on the application’s classpath.

Default Gson instance

Spring Boot once find the Gson dependency in the classpath, It automatically creates a Gson bean with some default configurations.

We can also autowire this dependency in our components See below code :

@Autowire
private Gson gson;

GsonAutoConfiguration class is responsible for the auto-configuration of the Gson instance in Spring Boot. It uses the annotation @ConditionalOnClass(Gson.class) to trigger the auto configuration.

Below is the class GsonAutoConfiguration :

/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure.gson;

import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

/**
 * {@link EnableAutoConfiguration Auto-configuration} for Gson.
 *
 * @author David Liu
 * @author Ivan Golovko
 * @since 1.2.0
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Gson.class)
@EnableConfigurationProperties(GsonProperties.class)
public class GsonAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean
	public GsonBuilder gsonBuilder(List<GsonBuilderCustomizer> customizers) {
		GsonBuilder builder = new GsonBuilder();
		customizers.forEach((c) -> c.customize(builder));
		return builder;
	}

	@Bean
	@ConditionalOnMissingBean
	public Gson gson(GsonBuilder gsonBuilder) {
		return gsonBuilder.create();
	}

	@Bean
	public StandardGsonBuilderCustomizer standardGsonBuilderCustomizer(GsonProperties gsonProperties) {
		return new StandardGsonBuilderCustomizer(gsonProperties);
	}

	static final class StandardGsonBuilderCustomizer implements GsonBuilderCustomizer, Ordered {

		private final GsonProperties properties;

		StandardGsonBuilderCustomizer(GsonProperties properties) {
			this.properties = properties;
		}

		@Override
		public int getOrder() {
			return 0;
		}

		@Override
		public void customize(GsonBuilder builder) {
			GsonProperties properties = this.properties;
			PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
			map.from(properties::getGenerateNonExecutableJson).toCall(builder::generateNonExecutableJson);
			map.from(properties::getExcludeFieldsWithoutExposeAnnotation)
					.toCall(builder::excludeFieldsWithoutExposeAnnotation);
			map.from(properties::getSerializeNulls).whenTrue().toCall(builder::serializeNulls);
			map.from(properties::getEnableComplexMapKeySerialization).toCall(builder::enableComplexMapKeySerialization);
			map.from(properties::getDisableInnerClassSerialization).toCall(builder::disableInnerClassSerialization);
			map.from(properties::getLongSerializationPolicy).to(builder::setLongSerializationPolicy);
			map.from(properties::getFieldNamingPolicy).to(builder::setFieldNamingPolicy);
			map.from(properties::getPrettyPrinting).toCall(builder::setPrettyPrinting);
			map.from(properties::getLenient).toCall(builder::setLenient);
			map.from(properties::getDisableHtmlEscaping).toCall(builder::disableHtmlEscaping);
			map.from(properties::getDateFormat).to(builder::setDateFormat);
		}

	}

}

Jackson is also configured in a similar way. JacksonAutoConfiguration is used for auto configuration of Jackson in Spring Boot application.

Custom Gson instance

Above is the default auto configuration for Gson but we can also customize the default behavior of Gson instance in Spring Boot.

According to requirement of application, we can configure any property mentioned in below list in the application.properties file.

GsonAutoConfiguration class uses these properties while initializing Gson.

See the list :

# Format to use when serializing Date objects.
spring.gson.date-format= 
 
# Whether to disable the escaping of HTML characters such as '<', '>', etc.
spring.gson.disable-html-escaping= 
 
# Whether to exclude inner classes during serialization.
spring.gson.disable-inner-class-serialization= 
 
# Whether to enable serialization of complex map keys (i.e. non-primitives).
spring.gson.enable-complex-map-key-serialization= 
 
# Whether to exclude all fields from consideration for serialization or deserialization that do not have the "Expose" annotation.
spring.gson.exclude-fields-without-expose-annotation= 
 
# Naming policy that should be applied to an object's field during serialization and deserialization.
spring.gson.field-naming-policy= 
 
# Whether to generate non executable JSON by prefixing the output with some special text.
spring.gson.generate-non-executable-json= 
 
# Whether to be lenient about parsing JSON that doesn't conform to RFC 4627.
spring.gson.lenient= 
 
# Serialization policy for Long and long types.
spring.gson.long-serialization-policy= 
 
# Whether to output serialized JSON that fits in a page for pretty printing.
spring.gson.pretty-printing= 
 
# Whether to serialize null fields.
spring.gson.serialize-nulls= 

Set Gson as preferred Json Mapper

We can add the below mentioned property in our application.properties file , If we want to make Gson as the Json mapper for our Spring Boot application rather than Jackson.

Below property to be added in application.properties :

##Property for making Gson as preferred Json Mapper
spring.http.converters.preferred-json-mapper=gson

Now whether or not Jackson is available in the application’s classpath, Spring Boot will use Gson for serializing and deserializing Json.

Exclude Jackson from Spring Boot

We can also exclude Jackson from our Spring Boot’s application. We can do it by excluding the spring-boot-starter-json .

See Below :

Excluding Jackson from Project Dependencies

To exclude the Jackson from Spring Boot applications project dependencies, we need to add below code in our pom.xml file :

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <!-- Exclude the default Jackson dependency -->
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-json</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>
</dependencies>

Disabling Auto-Configuration

In case, we want to exclude Jackson only inside spring boot configuration then we need to disable the class JacksonAutoConfiguration which is auto-configuration class for Jackson.

MainApp.java :

@SpringBootApplication(exclude = {JacksonAutoConfiguration.class})
public class MainApp{
 
    public static void main(String[] args) {
        SpringApplication.run(MainApp.class, args);
    }
}

Conclusion

We have learnt complete tutorial for Gson with Spring Boot, What It is, Its configuration and customization as preferred Json mapper and also How to exclude Jackson, which is by default used in Spring Boot , from your project.

Leave a Reply

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