Gson with Spring boot 2

Learn to configure Gson with spring boot applications as preferred json mapper. By default, Spring boot uses Jackson for this purpose.

1. Include Gson dependency

Include gson in the spring boot application by adding the appropriate Gson dependency.

dependencies {
    compile group: '', name: 'gson', version: '2.8.5'

2. Gson auto-configuration

With dependency inclusion, Spring Boot detects Gson dependency on the classpath and creates a Gson bean with sensible defaults.

2.1. Default Gson instance

Spring boot detects presence of Gson.class and uses GsonAutoConfiguration for configuring the Gson instance.

If we need direct access to Gson instance, we can directly autowire in spring beans:

private Gson gson;

2.2. Custom Gson instance

To customize the default behavior of Gson instance, configure the respective property from below list. GsonAutoConfiguration uses these properties while initializing the Gson instance.

# Format to use when serializing Date objects. 

# Whether to disable the escaping of HTML characters such as '<', '>', etc.

# Whether to exclude inner classes during serialization.

# Whether to enable serialization of complex map keys (i.e. non-primitives).

# Whether to exclude all fields from consideration for serialization or deserialization that do not have the "Expose" annotation.

# Naming policy that should be applied to an object's field during serialization and deserialization.

# Whether to generate non executable JSON by prefixing the output with some special text.

# Whether to be lenient about parsing JSON that doesn't conform to RFC 4627.

# Serialization policy for Long and long types.

# Whether to output serialized JSON that fits in a page for pretty printing.

# Whether to serialize null fields.

3. Make Gson preferred json mapper

To configure spring boot to use Gson as preferred mapper over Jackson, use this property in file.


Now even if Jackson is available in classpath, Spring boot will use Gson to serialize and deserialize JSON payloads.

4. Exclude Jackson completely

If we want to exclude Jackson completely from application runtime, we can do it by exluding spring-boot-starter-json.

4.1. Exclude Jackson from project dependencies

        <!-- Exclude the default Jackson dependency -->

4.2. Disable auto-configuration

If we want to exclude Jackson only inside spring boot configuration, we can exclude it by disabling it’s auto configuration class JacksonAutoConfiguration.

@SpringBootApplication(exclude = {JacksonAutoConfiguration.class})
public class SpringBootApplication {

    public static void main(String[] args) {, args);

Drop me your questions related to configure Gson with Spring boot 2.

Happy Learning !!

Comments are closed for this article!

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.