SpringBoot解决LocalDateTime

项目场景:开发问题记录

例如: 前端传入时间报错,无法反序列化。向前端返回时间需要格式化


问题描述

前端传入的时间无法反序列化,向前端返回格式化时间

Cannot deserialize value of type `java.time.LocalDateTime` from String "2023-04-06 14:33:33": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2023-04-06 14:33:33' could not be parsed at index 10
 at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 4, column: 18] (through reference chain: com.taiji.businessdomain.stmbsscpacdc.client.api.dto.persist.PersistExpressInfoRequest["updatedAt"])

 Cannot deserialize value of type `java.time.LocalDateTime` from String "2023-04-06 14:33:33": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2023-04-06 14:33:33' could not be parsed at index 10
 at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 4, column: 18] (through reference chain: com.taiji.businessdomain.stmbsscpacdc.client.api.dto.persist.PersistExpressInfoRequest["updatedAt"])


原因分析:

提示:这里填写问题的分析:

时间格式导致无法反序列化,前端时间默认格式一般为“2023-04-06T14:33:14.997Z”,而"2023-04-06 14:33:33"这种时间格式化无法接收


解决方案1:

提示:这里填写该问题的具体解决方案:

直接在属性上加上注解

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")

 

解决方案2:

提示:这里填写该问题的具体解决方案:

通过jackson来自定义一个全局类型处理,通过序列化可以将返回前端的时间进行格式化,反序列化将前端传来的时间进行格式化

package com.taiji.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@Configuration
public class LocalDateTimeSerializerConfig {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            //序列化
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            //反序列化
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer());
        };
    }

    /**
     * 反序列化
     */
        public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)
                throws IOException {
            long timestamp = p.getValueAsLong();
            if (timestamp > 0) {
                return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
            } else {
                return null;
            }
        }
    }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot应用程序中使用MyBatis时,可以使用TypeHandler来解决LocalDateTime类型的全局配置时间转换问题。 首先,创建一个实现了TypeHandler接口的类,例如:LocalDateTimeTypeHandler。 ``` public class LocalDateTimeTypeHandler implements TypeHandler<LocalDateTime> { @Override public void setParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException { if (parameter != null) { ps.setTimestamp(i, Timestamp.valueOf(parameter)); } else { ps.setNull(i, Types.TIMESTAMP); } } @Override public LocalDateTime getResult(ResultSet rs, String columnName) throws SQLException { Timestamp timestamp = rs.getTimestamp(columnName); return getLocalDateTime(timestamp); } @Override public LocalDateTime getResult(ResultSet rs, int columnIndex) throws SQLException { Timestamp timestamp = rs.getTimestamp(columnIndex); return getLocalDateTime(timestamp); } @Override public LocalDateTime getResult(CallableStatement cs, int columnIndex) throws SQLException { Timestamp timestamp = cs.getTimestamp(columnIndex); return getLocalDateTime(timestamp); } private LocalDateTime getLocalDateTime(Timestamp timestamp) { if (timestamp != null) { return timestamp.toLocalDateTime(); } return null; } } ``` 然后,在MyBatis的配置文件中将该TypeHandler注册为全局TypeHandler。 ``` <configuration> <typeHandlers> <typeHandler handler="com.example.LocalDateTimeTypeHandler"/> </typeHandlers> </configuration> ``` 这样,在使用LocalDateTime类型的时候,MyBatis就会自动调用该TypeHandler进行转换。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值