springmvc java8时间处理

需要引入的依赖


    com.fasterxml.jackson.datatype
    jackson-datatype-jsr310
// 取消默认的ObjectMapper对象,自定义一个
@Bean
public ObjectMapper objectMapper() {
    val objectMapper = new ObjectMapper();
    // 格式化器
    val localDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    val localDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    val localTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
    val javaTimeModule = new JavaTimeModule();
    // java8新特性 解决optional的输出问题
    val jdk8Module = new Jdk8Module();
    // 注册模块
    objectMapper.registerModules(javaTimeModule, jdk8Module);

    // 序列化配置
    javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(localDateFormatter));
    javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(localDateTimeFormatter));
    javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(localTimeFormatter));
    // 配置Date序列化格式
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    // 配置序列化的包含项,null值不输出
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // 反序列化设置
    javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(localDateFormatter));
    javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(localDateTimeFormatter));
    javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(localTimeFormatter));
    return objectMapper;
}

 

你可能感兴趣的:(spring)