Commit 019d5fb473cea6dec6d35628678aa7a68a3265d4
1 parent
1a7a2182
feat:【framework】增加对 LocalDateTime 类型格式化不生效问题 #1019
Showing
1 changed file
with
17 additions
and
1 deletions
yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/json/databind/TimestampLocalDateTimeSerializer.java
| 1 | package cn.iocoder.yudao.framework.common.util.json.databind; | 1 | package cn.iocoder.yudao.framework.common.util.json.databind; |
| 2 | 2 | ||
| 3 | +import com.fasterxml.jackson.annotation.JsonFormat; | ||
| 3 | import com.fasterxml.jackson.core.JsonGenerator; | 4 | import com.fasterxml.jackson.core.JsonGenerator; |
| 4 | import com.fasterxml.jackson.databind.JsonSerializer; | 5 | import com.fasterxml.jackson.databind.JsonSerializer; |
| 5 | import com.fasterxml.jackson.databind.SerializerProvider; | 6 | import com.fasterxml.jackson.databind.SerializerProvider; |
| 7 | +import org.apache.commons.lang3.reflect.FieldUtils; | ||
| 6 | 8 | ||
| 7 | import java.io.IOException; | 9 | import java.io.IOException; |
| 10 | +import java.lang.reflect.Field; | ||
| 8 | import java.time.LocalDateTime; | 11 | import java.time.LocalDateTime; |
| 9 | import java.time.ZoneId; | 12 | import java.time.ZoneId; |
| 13 | +import java.time.format.DateTimeFormatter; | ||
| 10 | 14 | ||
| 11 | /** | 15 | /** |
| 12 | * 基于时间戳的 LocalDateTime 序列化器 | 16 | * 基于时间戳的 LocalDateTime 序列化器 |
| @@ -19,7 +23,19 @@ public class TimestampLocalDateTimeSerializer extends JsonSerializer<LocalDateTi | @@ -19,7 +23,19 @@ public class TimestampLocalDateTimeSerializer extends JsonSerializer<LocalDateTi | ||
| 19 | 23 | ||
| 20 | @Override | 24 | @Override |
| 21 | public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { | 25 | public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { |
| 22 | - // 将 LocalDateTime 对象,转换为 Long 时间戳 | 26 | + String fieldName = gen.getOutputContext().getCurrentName(); |
| 27 | + Class<?> clazz = gen.getOutputContext().getCurrentValue().getClass(); | ||
| 28 | + Field field = FieldUtils.getField(clazz, fieldName, true); | ||
| 29 | + // 情况一:有 JsonFormat 自定义注解,则使用它。https://github.com/YunaiV/ruoyi-vue-pro/pull/1019 | ||
| 30 | + JsonFormat[] jsonFormats = field.getAnnotationsByType(JsonFormat.class); | ||
| 31 | + if (jsonFormats.length > 0) { | ||
| 32 | + String pattern = jsonFormats[0].pattern(); | ||
| 33 | + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); | ||
| 34 | + gen.writeString(formatter.format(value)); | ||
| 35 | + return; | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + // 情况二:默认将 LocalDateTime 对象,转换为 Long 时间戳 | ||
| 23 | gen.writeNumber(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); | 39 | gen.writeNumber(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); |
| 24 | } | 40 | } |
| 25 | 41 |