Gson with Spring Boot: Dependency and Example

Lokesh Gupta

Learn to configure Google Gson with Spring Boot applications as the preferred JSON mapper to serialize and deserialize Java objects to JSON.

By default, Spring Boot uses Jackson for JSON serialization and deserialization.

1. Include Gson Dependency

Include Gson in the Spring boot application by adding the latest version of com.google.code.gson:gson artifact.

dependencies {
    compile group: 'com.google.code.gson', name: 'gson', version: '2.10.1'
}
<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.10.1</version>
</dependency>

2. Spring Boot Autoconfiguration for Gson

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

2.1. Default Gson Bean is Created Automatically

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

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

@Autowire
private Gson gson;

2.2. Customizing the Gson Bean using Properties Configuration

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

# Format to use when serializing Date objects.
spring.gson.date-format= 

# Whether to disable the escaping of HTML characters such as '&lt;', '&gt;', 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 &quot;Expose&quot; 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=

2.3. Customizing the Gson Bean using Java Configuration

To customize the Gson bean using Java configuration, we can create a @Bean definition for it in our @Configuration class and apply any desired custom settings.

@Bean
public Gson gson() {
  // Create a GsonBuilder to configure Gson
  GsonBuilder gsonBuilder = new GsonBuilder();

  // Add custom Gson configuration here
  gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");
  gsonBuilder.serializeNulls();

  // Create and return the custom Gson instance
  return gsonBuilder.create();
}

3. Replacing Jackson with Gson as Default JSON Mapper

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

spring.http.converters.preferred-json-mapper=gson

Now, even if Jackson is available in the classpath, Spring Boot will use GsonHttpMessageConverter to serialize and deserialize JSON payloads.

We can further customize the GsonHttpMessageConverter bean to be used in Spring MVC applications for automatic request and response parsing.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

  @Bean
  public Gson gson() {
    GsonBuilder gsonBuilder = new GsonBuilder()
      .setDateFormat("yyyy-MM-dd HH:mm:ss")
      .serializeNulls();

    return gsonBuilder.create();
  }

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

    GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
    gsonHttpMessageConverter.setGson(gson());
    converters.add(gsonHttpMessageConverter);
  }
}

4. Excluding 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

<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.10.1</version>
  </dependency>
</dependencies>

4.2. Disable Jackson Autoconfiguration

If we want to exclude Jackson only through the spring boot configuration, we can exclude it by disabling its auto configuration class JacksonAutoConfiguration.

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

Drop me your questions related to configuring Gson with Spring boot 3.

Happy Learning !!

Comments

Subscribe
Notify of
guest
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

Dark Mode

Dark Mode