Spring Boot 配置ObjectMapper处理JSON序列化

添加配置类

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.databind.DeserializationFeature;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JsonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 不报错于未知属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 仅在属性不为NULL时序列化
        objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
        // 注册Java 8日期/时间模块
        objectMapper.registerModule(new JavaTimeModule());
        // 时间类型转换成时间戳
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        return objectMapper;
    }

}

你可能感兴趣的:(spring,boot,spring,boot,1024程序员节)