Springboot统一配置Jackson

经常要为接口响应对象设置属性,序列化的时候是不是包含空值,反序列化的时候是否忽略不认识的字段。所以,必须要手动制定ObjectMapper或者在类上声明

@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)

虽然不算复杂,但既然统一了规则,那就来个统一设定吧。

在springboo1.5+以上的版本可以这么设置Jackson的一些属性配置

spring:
  jackson:
    serialization:
      WRITE_DATES_AS_TIMESTAMPS: false
    default-property-inclusion: non_null

更多配置参见 org.springframework.boot.autoconfigure.jackson.JacksonProperties


@ConfigurationProperties(
    prefix = "spring.jackson"
)
public class JacksonProperties {
    private String dateFormat;
    private String jodaDateTimeFormat;
    private String propertyNamingStrategy;
    private Map<SerializationFeature, Boolean> serialization = new HashMap();
    private Map<DeserializationFeature, Boolean> deserialization = new HashMap();
    private Map<MapperFeature, Boolean> mapper = new HashMap();
    private Map<Feature, Boolean> parser = new HashMap();
    private Map<com.fasterxml.jackson.core.JsonGenerator.Feature, Boolean> generator = new HashMap();
    private Include defaultPropertyInclusion;
    private TimeZone timeZone = null;
    private Locale locale;
    
    //省略
}

LocalDateTime统一序列化

配置类

@Configuration
public class LocalDateTimeSerializerConfig {
    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }

}

配置文件

spring:
  profiles:
    active: dev
  jackson:
    default-property-inclusion: non_null
    date-format: "yyyy-MM-dd HH:mm:ss"
    joda-date-time-format: "yyyy-MM-dd HH:mm:ss"
    time-zone: "Asia/Shanghai"
    serialization:
      WRITE_DATES_AS_TIMESTAMPS: false

单独jackson注解修改特殊的序列化

posted @ 2018-07-03 17:18  Ryan.Miao  阅读(17186)  评论(0编辑  收藏  举报