Springboot integrates Json (Jackson, Gson, FastJson)

Article directory

  • There are three ways to integrate json with springboot. Springboot uses jackson by default. If you want to use the other two, you need to exclude jackson
    • 1.springboot integrates jackson
      • 1.1 pom.xml
      • 1.2 Entity classes, the use of jackson annotations
      • 1.3 controller
      • 1.4 jackson global configuration
    • 2. springboot integrates gson
      • 2.1 pom.xml
      • 2.2 Entity class
      • 2.3 controller
      • 2.4 Global configuration method of gson
        • 2.4.1 application.[properties](https://so.csdn.net/so/search?q=properties &spm=1001.2101.3001.7020)
        • 2.4.2 Through the configuration file, provide a GsonBuilder or converter Bean
    • 3.springboot integrates fastjson
      • 3.1 pom.xml
      • 3.2 Entity class
      • 3.3 controller
      • 3.4 Configuration of fastjson
    • 3. Summary

There are three ways to integrate json with springboot. Springboot uses jackson by default. If you want to use the other two, you need to exclude jackson

1.springboot integrates jackson

1.1 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yl</groupId>
    <artifactId>springbootjackson</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootjackson</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1.2 Entity classes, use of jackson annotations

package com.yl.springbootjackson.model;

import com.fasterxml.jackson.annotation.*;

import java.util.Date;

//Batch ignore attributes during serialization/deserialization
@JsonIgnoreProperties({<!-- -->"score","message"})
public class User {<!-- -->
    @JsonProperty(index = 92)
    private String name;
    //Ignore a certain attribute when serializing/deserializing
    @JsonIgnore
    private Integer sex;
    //Specify the name of the attribute when serializing/deserializing, the default is the attribute name, value specifies the new attribute name, index is mainly used for sorting
    @JsonProperty(value = "aage",index = 91)
    //Similar to index in JsonProperty, used for sorting
    //@JsonPropertyOrder()
    private int age;
    @JsonProperty(index = 90)
    //Date formatting, pay attention to time zone issues
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
    private Date birth;
    @JsonProperty(index = 89)
    private Integer score;
    @JsonProperty(index = 88)
    private String message;


    public String getName() {<!-- -->
        return name;
    }

    public void setName(String name) {<!-- -->
        this.name = name;
    }

    public int getAge() {<!-- -->
        return age;
    }

    public void setAge(int age) {<!-- -->
        this. age = age;
    }

    public Date getBirth() {<!-- -->
        return birth;
    }

    public void setBirth(Date birth) {<!-- -->
        this.birth = birth;
    }

    @Override
    public String toString() {<!-- -->
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birth=" + birth +
                '}';
    }
}

1.3 controller

package com.yl.springbootjackson.controller;

import com.yl.springbootjackson.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class UserController {<!-- -->

    @GetMapping("/getUser")
    public User getUser() {<!-- -->
        User user = new User();
        user.setName("Xiaolan");
        user.setAge(19);
        user.setBirth(new Date());
        return user;
    }

    @PostMapping("/save")
    public void save(@RequestBody User user) {<!-- -->
        System.out.println(user);
    }

 }

1.4 jackson global configuration

package com.yl.springbootjackson.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;

/**
 * jackson global configuration method, just inject ObjectMapper
 */
@Configuration
public class WebMVCConfig {<!-- -->
    @Bean
    ObjectMapper objectMapper() {<!-- -->
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return objectMapper;
    }
}

2.springboot integrates gson

2.1 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yl</groupId>
    <artifactId>springbootgson</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootgson</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!--Exclude jackson dependency-->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--gson dependency-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.2 Entity class

package com.yl.springbootgson.model;

import com.google.gson.annotations.Expose;

import java.util.Date;

public class User {<!-- -->
    @Expose
    private String name;
    @Expose
    private Date birth;

    public String getName() {<!-- -->
        return name;
    }

    public void setName(String name) {<!-- -->
        this.name = name;
    }

    public Date getBirth() {<!-- -->
        return birth;
    }

    public void setBirth(Date birth) {<!-- -->
        this.birth = birth;
    }
}

2.3 controller

package com.yl.springbootgson.controller;

import com.yl.springbootgson.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class UserController {<!-- -->

    @GetMapping("/getUser")
    public User getUser() {<!-- -->
        User user = new User();
        user.setName("Xiaonan");
        user.setBirth(new Date());
        return user;
    }
}

2.4 Global configuration method of gson

2.4.1 application.properties

spring.gson.date-format=yyyy-MM-dd HH:mm:ss
# Whether to disable HTML escape characters
spring.gson.disable-html-escaping=true
# Whether to exclude inner classes during serialization
spring.gson.disable-inner-class-serialization=false
# Whether to discard complex map keys during serialization
spring.gson.enable-complex-map-key-serialization=
# Whether to exclude fields without @Expose annotation
spring.gson.exclude-fields-without-expose-annotation=true
# Naming strategy for field names during serialization
spring.gson.field-naming-policy=lower_case_with_underscores
# Add some special text before output to generate a non-executable json
spring.gson.generate-non-executable-json=
# Whether to serialize empty fields
spring.gson.serialize-nulls=false

2.4.2 Provide a GsonBuilder or converter Bean through the configuration file

package com.yl.springbootgson.config;

import com.google.gson.GsonBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Customize a GsonBuilder and configure some gson attributes
 */
@Configuration
public class WebMVCConfig {<!-- -->
    @Bean
    GsonBuilder gsonBuilder() {<!-- -->
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("yyyy-MM-dd");
        return gsonBuilder;
    }
}

3.springboot integrates fastjson

3.1 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yl</groupId>
    <artifactId>fastjson</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>fastjson</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--fastjson dependency-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3.2 Entity class

package com.yl.fastjson.model;

import java.util.Date;

public class User {<!-- -->
    private String name;
    private Date birth;
    private Integer sex;

    public String getName() {<!-- -->
        return name;
    }

    public void setName(String name) {<!-- -->
        this.name = name;
    }

    public Date getBirth() {<!-- -->
        return birth;
    }

    public void setBirth(Date birth) {<!-- -->
        this.birth = birth;
    }

    public Integer getSex() {<!-- -->
        return sex;
    }

    public void setSex(Integer sex) {<!-- -->
        this.sex = sex;
    }
}

3.3 controller

package com.yl.fastjson.controller;

import com.yl.fastjson.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class UserController {<!-- -->

    @GetMapping("/getUser")
    public User user() {<!-- -->
        User user = new User();
        user.setName("Xiaobai");
        user.setBirth(new Date());
        user.setSex(0);
        return user;
    }
}

3.4 fastjson configuration

package com.yl.fastjson.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * If you want to use fastjson, you must provide a Converter
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {<!-- -->

    //Method 1: Inherit WebMvcConfigurer, rewrite configureMessageConverters, and add converter to converters
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {<!-- -->
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        List supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        supportedMediaTypes.add(MediaType.APPLICATION_PDF);
        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.IMAGE_GIF);
        supportedMediaTypes.add(MediaType.IMAGE_JPEG);
        supportedMediaTypes.add(MediaType.IMAGE_PNG);
        supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        supportedMediaTypes.add(MediaType.TEXT_XML);
        converter.setSupportedMediaTypes(supportedMediaTypes);
        FastJsonConfig config = converter.getFastJsonConfig();
        config.setCharset(Charset.forName("UTF-8"));
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteClassName);
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(converter);
    }

    //Method 2: Register a Bean
// @Bean
// FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {<!-- -->
// FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
// List supportedMediaTypes = new ArrayList<>();
// supportedMediaTypes.add(MediaType.APPLICATION_JSON);
// supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
// supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
// supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
// supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
// supportedMediaTypes.add(MediaType.APPLICATION_PDF);
// supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
// supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
// supportedMediaTypes.add(MediaType.APPLICATION_XML);
// supportedMediaTypes.add(MediaType.IMAGE_GIF);
// supportedMediaTypes.add(MediaType.IMAGE_JPEG);
// supportedMediaTypes.add(MediaType.IMAGE_PNG);
// supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
// supportedMediaTypes.add(MediaType.TEXT_HTML);
// supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
// supportedMediaTypes.add(MediaType.TEXT_PLAIN);
// supportedMediaTypes.add(MediaType.TEXT_XML);
// converter.setSupportedMediaTypes(supportedMediaTypes);
// FastJsonConfig config = converter. getFastJsonConfig();
// config.setCharset(Charset.forName("UTF-8"));
// config.setDateFormat("yyyy-MM-dd HH:mm:ss");
// config.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteClassName);
// converter.setFastJsonConfig(config);
// converter.setDefaultCharset(Charset.forName("UTF-8"));
// return converter;
// }
}

3. Summary

3.1 springboot uses jackson by default, and automatically configures both jackson and gson, so generally use one of the two. If you must have fastjson, you must register FastJsonHttpMessageConverter in the container or implement the WebMvcConfigurer interface to rewrite the configureMessageConverters method and add the FastJsonHttpMessageConverter object to the converters collection.
3.2 In addition, we can also customize the converter of jackson or gson, and then set some properties we need in it, and then register it in the container to use it.