package cn.iocoder.yudao.framework.common.util.json.databind; import tools.jackson.core.JacksonException; import tools.jackson.core.JsonParser; import tools.jackson.core.JsonToken; import tools.jackson.databind.DeserializationContext; import tools.jackson.databind.ValueDeserializer; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; /** * 基于时间戳的 LocalDateTime 反序列化器 * * @author 老五 */ public class TimestampLocalDateTimeDeserializer extends ValueDeserializer { public static final TimestampLocalDateTimeDeserializer INSTANCE = new TimestampLocalDateTimeDeserializer(); private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @Override public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws JacksonException { // 数字类型:作为时间戳处理 if (p.currentToken() == JsonToken.VALUE_NUMBER_INT) { return LocalDateTime.ofInstant(Instant.ofEpochMilli(p.getValueAsLong()), ZoneId.systemDefault()); } // 字符串类型:先尝试作为时间戳解析,再按日期格式解析 String text = p.getValueAsString(); try { long millis = Long.parseLong(text); return LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); } catch (NumberFormatException e) { // 不是纯数字,按默认日期格式解析 } return LocalDateTime.parse(text, DEFAULT_FORMATTER); } }