项目场景:开发问题记录
例如: 前端传入时间报错,无法反序列化。向前端返回时间需要格式化
问题描述
前端传入的时间无法反序列化,向前端返回格式化时间
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;
}
}
}
}