fix(json): 修复时间戳序列化时字段为空的问题

- 使用 ObjectUtil 判断字段名是否为空
- 增加对反射获取字段的空值检查
- 避免因字段为空导致的序列化异常
pull/225/head
wuKong 2025-12-19 16:56:21 +08:00
parent ec8577bdd9
commit 19bf9ca935
1 changed files with 10 additions and 7 deletions

View File

@ -1,5 +1,6 @@
package cn.iocoder.yudao.framework.common.util.json.databind;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
@ -25,15 +26,17 @@ public class TimestampLocalDateTimeSerializer extends JsonSerializer<LocalDateTi
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
// 情况一:有 JsonFormat 自定义注解则使用它。https://github.com/YunaiV/ruoyi-vue-pro/pull/1019
String fieldName = gen.getOutputContext().getCurrentName();
if (fieldName != null) {
if (ObjectUtil.isNotNull(fieldName)) {
Class<?> clazz = gen.getOutputContext().getCurrentValue().getClass();
Field field = ReflectUtil.getField(clazz, fieldName);
JsonFormat[] jsonFormats = field.getAnnotationsByType(JsonFormat.class);
if (jsonFormats.length > 0) {
String pattern = jsonFormats[0].pattern();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
gen.writeString(formatter.format(value));
return;
if (ObjectUtil.isNotNull(field)) {
JsonFormat[] jsonFormats = field.getAnnotationsByType(JsonFormat.class);
if (jsonFormats.length > 0) {
String pattern = jsonFormats[0].pattern();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
gen.writeString(formatter.format(value));
return;
}
}
}