Jackson 2.x 系列【31】Spring Boot 集成之字典回写
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
// 配置自动将字段转为下划线命名
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
// 配置时间序列化和反序列化处理
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
mapper.registerModule(javaTimeModule);
// 配置序列化时忽略空值字段
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
// 其他配置...
return mapper;
}
}
这个配置类中定义了一个ObjectMapper
的Bean,用于在Spring Boot项目中集成Jackson进行字段的下划线命名和时间的序列化。同时,配置了序列化时忽略空值字段的选项。这样,在Spring Boot应用中,Jackson的这些配置将会被应用,从而简化应用的配置并提高代码质量。
评论已关闭