1. SpringBoot JSON工具包默认是Jackson,只需要引入spring-boot-starter-web依赖包,自动引入相应依赖包:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> -->数据绑定依赖于下面两个包 <version>2.8.7</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> -->注解包 <version>2.8.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> -->核心包 <version>2.8.7</version> </dependency>
2. Jackson两种配置方式
A. application.properties文件
# 日期格式化 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss # 日期时区 spring.jackson.time-zone=GMT+8 # 返回值null不显示 spring.jackson.default-property-inclusion=non_null
B. bean配置
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; @Configuration public class JacksonConfig { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // 返回值过滤null或""值 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY).setSerializationInclusion(JsonInclude.Include.NON_NULL); return objectMapper; } }