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.LocalDate; import java.time.ZoneId; import java.time.format.DateTimeFormatter; /** * 基于时间戳的 LocalDate 反序列化器 * 兼容:数字时间戳、字符串时间戳、日期字符串 * * @author 老五 */ public class TimestampLocalDateDeserializer extends ValueDeserializer { public static final TimestampLocalDateDeserializer INSTANCE = new TimestampLocalDateDeserializer(); private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd"); @Override public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws JacksonException { if (p.currentToken() == JsonToken.VALUE_NUMBER_INT) { return LocalDate.ofInstant(Instant.ofEpochMilli(p.getValueAsLong()), ZoneId.systemDefault()); } String text = p.getValueAsString(); try { long millis = Long.parseLong(text); return LocalDate.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); } catch (NumberFormatException e) { // 不是纯数字,按日期格式解析 } return LocalDate.parse(text, DEFAULT_FORMATTER); } }