Springboot JackSon

Posted King-D

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot JackSon相关的知识,希望对你有一定的参考价值。

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;
   }

}

 

以上是关于Springboot JackSon的主要内容,如果未能解决你的问题,请参考以下文章

#yyds干货盘点#jackson学习之九:springboot整合(配置文件)

SpringBoot + Jackson + Kotlin 数据类:忽略字段注释

springboot之jackson的两种配置方式

Springboot JackSon

Azure + SpringBoot 'com/fasterxml/jackson/core/JsonFactory'

SpringBoot全局Jackson配置未生效