Please please please please please please please please please please please please hurry! Some attention

In this article, you’ll learn how to use Google Gson in Spring Boot. Gson is an open source Java library for serializing and deserializing Java objects to JSON.

Spring Boot uses Jackson as the default library to serialize and deserialize Java objects to JSON. If you add “spring-boot-starter” to your application, it will be included in your classpath. This is great, but sometimes you might want to use an API other than the one available in Spring Boot automatic configuration. In this article, we will walk you through the steps to use Gson and Spring Boot.

Spring Boot is a smart system with some default values that has Gson’s auto-configuration capabilities. Once Gson is found on the classpath, Spring Boot will automatically configure the Gson bean. It also provides several Gson-specific properties in the application.properties file.

1. The Maven dependencies

Our first step in configuration is to add Gson dependencies to our POM.xml file. This is what our POM.xml file looks like:

<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> <! -- check latest versionfor GSON -->
</dependency>
Copy the code

With the above configuration, Spring Boo creates a Gson bean with reasonable defaults. Spring provides a Gson HttpMessageconverter that can read and write JSON using the Google Gson library.

1.1 Use Gson as the default Mapper

We include Gson in the classpath, but we need to use the application.properties file to set Gson as the preferred mapper.

spring.http.converters.preferred-json-mapper=gson #Preferred JSON mapper to use for HTTP message conversion.
Copy the code

If you don’t have a preferred JSON mapper set, you might run into one

org.springframework.http.converter.HttpMessageNotWritableException.
Copy the code
1.2 Gson configuration

Spring Boot provides several properties for the Gson configuration. Here’s the list reference:

The format used to serialize the date object.
spring.gson.date-format= 

# Whether to disable HTML character escaping, 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 mapping keys (that is, non-primitives).
spring.gson.enable-complex-map-key-serialization=

Whether to serialize or deserialize all fields that do not have an "expose" comment.
spring.gson.exclude-fields-without-expose-annotation= 

The naming strategy applied to object fields during serialization and deserialization.
spring.gson.field-naming-policy= 

Whether to generate unexecutable JSON by adding some special text before output.
spring.gson.generate-non-executable-json= 

Parsing JSON that does not conform to RFC 4627 is tolerated.
spring.gson.lenient= 

Long types and serialization strategies for long types.
spring.gson.long-serialization-policy= 

Output serialized JSON suitable for beautiful printed pages.
spring.gson.pretty-printing=

Whether to serialize empty fields.
spring.gson.serialize-nulls= 
Copy the code

2. Eliminate Jackson’s dependency

If you use Gson as the default library, remove Jackson from the classpath. There are two ways to exclude it from the classpath

2.1 use Maven

The easiest way to do this is to use your exclusion tag pom.xml. Spring Boot adds Jackson as part of the Web launcher, and all we need is to exclude him from the Web launcher.

<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> < the groupId > com. Google. Code. Gson < / groupId > < artifactId > gson < / artifactId > < version > 2.8.5 < / version > < / dependency > </dependencies>Copy the code
2.1 Exclude is used

The second method is to use a exclude attribute with either @enableAutoConfiguration or @SpringBootApplication

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

Use this option, you can skip Settings, spring. HTTP. Converters. The preferred – json – mapper because spring Boot configuration only a mapper

3. Customize using HttpMessageConverters

To customize the behavior of the Gson mapper in a Spring Boot application, you can extend the WebMvcConfigurerAdapter to get the Http message converter with Spring. We’ll illustrate how we want to customize the date format for the JSON converter.

@Configuration public class ApplicationConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<? >> converters) { converters.add(customGsonHttpMessageConverter()); super.configureMessageConverters(converters); } private GsonHttpMessageConvertercustomGsonHttpMessageConverter() {
        Gson gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'")
                .create();

        GsonHttpMessageConverter gsonMessageConverter = new GsonHttpMessageConverter();
        gsonMessageConverter.setGson(gson);

        returngsonMessageConverter; }}Copy the code

Unit testing

Let’s set up a small unit test case to test the Gson converter.

@RunWith(SpringRunner.class)
@SpringBootTest
public class GsonSpringBootApplicationTests {

    private Product product;

    @Before
    public void setup(){
        product =new  Product("123"."Demo Product", 123); } @Test public void simpleGsonTest() throws JSONException { String expected ="{\n" +
                "\" code \ ": \ 蕋 \", \ n" +
                "\"name\": \"Demo Product\",\n" +
                "\"price\": 123\n" +
                "}";

        Gson gson = new GsonBuilder().create();
        String data= gson.toJson(product);

        JSONAssert.assertEquals(expected,data,false);
    }

    @Test
    public void errorGsonTest() throws JSONException {
        String expected = "{\n" +
                "\" code \ ": \ 񓓱 \", \ n" +
                "\"name\": \"Demo Product\",\n" +
                "\"price\": 123\n" +
                "}";

        Gson gson = new GsonBuilder().create();
        String data= gson.toJson(product);

        JSONAssert.assertEquals(expected,data,false); }}Copy the code

Welcome to our fan base: In 963944895, Free sharing of Spring framework, Mybatis framework SpringBoot framework, SpringMVC framework, SpringCloud microservice, Dubbo framework, Redis cache, RabbitMq messages, JVM tuning, Tomcat container, MySQL database teaching video and rack Construct a learning mind map

Write at the end:

Bald programmer is not easy, see here, the point of concern! Point attention, do not get lost, continue to update!!