关于spring boot时间格式问题,已经做了序列化了,还是报错


com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 
Java 8 date/time type `java.time.LocalDateTime` not supported by default:
 add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" 
to enable handling (through reference chain: 
com.yuan.employment.websocket.result.ResultMessage["message"]->java.util.ArrayList[0]->java.util.HashMap["lasttime"])

序列化:

@Configuration
public class LocalDateTimeConfiguration {
    final private String pattern = "yyyy-MM-dd HH:mm:ss";

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

            //返回时间数据序列化
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
            //接收时间数据反序列化
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        };
    }

}

实体类:

//后端发送给前端的消息类型
public class ResultMessage {
    private boolean isSystem;
    private String type;//系统消息的类型 CHANGESTATUS:改变用户在线状态   ALLSPECLIALIST所有用户 SPE-OFF-Line专家下线
    private String fromName;
    //private String toName;
    private Object message;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createtime;

    public ResultMessage(boolean isSystem, String type, String fromName, Object message) {
        this.isSystem = isSystem;
        this.type = type;
        this.fromName = fromName;
        this.message = message;
        this.createtime = new Date();
    }
}

报错提示是核心:

Java 8 date/time type `java.time.LocalDateTime` not supported by default

这里的提示明显说明在默认情况下是不支持这个类型。

另外,我怀疑你搞错了方向,、
看提示是【message】字段出现了问题,
而你处理的是createTime字段。

你看看设置的地方。

日期类Date使用SimpleDateFormat格式化(注意线程不安全),bean注入Jackson2ObjectMapperBuilderCustomizer时要格外注意;
日期类LocalDateTime使用DateTimeFormatter格式化(线程安全)。

createtime这个参数是不是有可能为null。