Use Gson with Spring Boot 4

Use Gson with Spring Boot 4.1.2. Compare an injected Gson bean with MVC JSON responses, customize LocalDate, and select Gson for the message converter.

Spring boot banner

Adding a Gson bean lets application code use Gson, but does not automatically make Spring MVC use Gson for controller responses. Spring Boot 4 uses Jackson 3 for JSON responses by default. This example shows both paths with the same catalog item, then switches the MVC message converter to Gson so the difference is visible in the response.

1. Add the Gson Starter

Use spring-boot-starter-webmvc for the HTTP endpoint and spring-boot-starter-gson for Gson integration. In Spring Boot 4, the Gson starter supplies the Gson library and its auto-configuration. Adding only com.google.code.gson:gson lets Java code import Gson, but it did not create the injectable Gson bean in the verified Boot 4.1.2 sample.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.1.2</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webmvc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-gson</artifactId>
    </dependency>
</dependencies>

The Spring Boot starter parent manages the compatible dependency versions. Jackson remains on the web application’s classpath. We will choose which JSON mapper MVC uses after we see the default behavior.

2. Create a Model That Makes the Mapper Visible

The catalog item has a Gson @SerializedName annotation. Gson writes code as item_code; Jackson does not use this Gson annotation. This gives us an observable distinction between the two serializers. The null note and date also let us check customization.

package com.howtodoinjava.gson;

import java.time.LocalDate;
import com.google.gson.annotations.SerializedName;

public class CatalogItem {
    @SerializedName("item_code")
    public String code = "P1";
    public String note = null;
    public LocalDate availableOn = LocalDate.of(2026, 11, 1);
}

The sample uses public fields only to keep the serialization difference easy to see. In an application with a richer model, use normal encapsulation and make the serializer’s field-access rules explicit. The date will be handled by a Gson type adapter in Section 4.

3. Inject Gson for an Explicit JSON Operation

Spring Boot creates a Gson bean when the Gson starter is present. A controller can inject that bean and call toJson() when it explicitly wants Gson output. The other endpoint returns the item itself, leaving response serialization to Spring MVC.

package com.howtodoinjava.gson;

import com.google.gson.Gson;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CatalogController {
    private final Gson gson;

    public CatalogController(Gson gson) {
        this.gson = gson;
    }

    @GetMapping("/catalog/item")
    public CatalogItem item() {
        return new CatalogItem();
    }

    @GetMapping(value = "/catalog/manual", produces = MediaType.APPLICATION_JSON_VALUE)
    public String manualJson() {
        return gson.toJson(new CatalogItem());
    }
}

The /catalog/manual method returns a JSON string generated by the injected bean. The declared application/json media type tells MVC to send that string as JSON. The /catalog/item method returns a Java object instead; MVC selects an HTTP message converter to serialize it. Therefore the presence of the injected Gson bean does not, by itself, prove that MVC uses Gson for the second endpoint.

In application.properties, enable null serialization for the auto-configured Gson bean:

server.address=127.0.0.1
server.port=9092
spring.gson.serialize-nulls=true

Without the last setting, Gson normally omits null-valued fields. Here the note field remains visible as "note":null, which helps us compare the two outputs. For more supported properties, see Spring Boot’s JSON configuration reference.

4. Customize Gson for LocalDate

Gson needs an adapter to serialize LocalDate reliably on current Java versions. A GsonBuilderCustomizer changes the auto-configured builder before Spring creates the Gson bean. This adapter writes the date as an ISO-8601 string:

package com.howtodoinjava.gson;

import java.time.LocalDate;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;
import org.springframework.boot.gson.autoconfigure.GsonBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GsonConfig {
    @Bean
    GsonBuilderCustomizer localDateAsIsoString() {
        return builder -> builder.registerTypeAdapter(LocalDate.class,
                (JsonSerializer<LocalDate>) (date, type, context) ->
                        new JsonPrimitive(date.toString()));
    }
}

The adapter affects the injected Gson bean, including /catalog/manual. It does not alter Jackson’s configuration. The customizer is separate from spring.gson.serialize-nulls because it installs a Java type adapter rather than setting one of Boot’s built-in Gson properties.

5. Compare the Default and Gson MVC Responses

The application starts with a small main class. Build the JAR and request both endpoints without activating any profile:

package com.howtodoinjava.gson;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GsonApplication {
    public static void main(String[] args) {
        SpringApplication.run(GsonApplication.class, args);
    }
}
mvn package
java -jar target/spring-boot-gson-demo-1.0.0.jar
curl http://127.0.0.1:9092/catalog/item
curl http://127.0.0.1:9092/catalog/manual

The verified default run returned these bodies. JSON field order is not significant, but the field names are:

{"availableOn":"2026-11-01","code":"P1","note":null}
{"item_code":"P1","note":null,"availableOn":"2026-11-01"}

The first response used Jackson because MVC serialized the returned CatalogItem. The second used the injected Gson bean because the controller called toJson() explicitly. The Gson annotation changes only the second response.

To make MVC prefer Gson as well, add application-gson.properties with the converter setting:

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

Stop the first process and start the JAR with the gson profile. Request the object-returning endpoint again:

java -jar target/spring-boot-gson-demo-1.0.0.jar --spring.profiles.active=gson
curl http://127.0.0.1:9092/catalog/item
# {"item_code":"P1","note":null,"availableOn":"2026-11-01"}

Now MVC’s JSON response uses Gson, so item_code appears in /catalog/item too. The profile is a convenient way to compare both modes in one project; an application that always uses Gson can put the setting in its regular application.properties file. This setting controls MVC and imperative HTTP message converters. It does not promise that every library in an application stops using Jackson internally.

6. FAQs

6.1. Should I exclude Jackson after selecting Gson for MVC?

Do not assume that switching the MVC mapper requires removing every Jackson dependency. Other integrations may still use Jackson directly. First verify the endpoint behavior with spring.http.converters.preferred-json-mapper=gson, then inspect the dependency tree and the requirements of other libraries before removing anything.

mvn dependency:tree

6.2. Why is @SerializedName ignored in my controller response?

Check which converter serialized the returned object. With the default Boot 4 MVC configuration, Jackson writes the response and does not interpret Gson’s annotation. The gson profile in this example changes the converter, so code becomes item_code.

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

7. Conclusion

Use the Gson starter for an injectable Gson bean and its spring.gson.* configuration. If controller responses must use Gson, set the MVC preferred mapper and verify a response that distinguishes the serializers. Keep Jackson dependencies until you know whether other parts of the application need them.

Happy Learning!

The complete runnable example is in the Spring Boot Gson project folder.

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.