| | |
| | | super(LocalDateTime.class); |
| | | } |
| | | |
| | | private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); |
| | | |
| | | @Override |
| | | public void serialize(LocalDateTime value, JsonGenerator gen, SerializationContext serializers) throws JacksonException { |
| | | // 情况一:有 JsonFormat 自定义注解,则使用它。https://github.com/YunaiV/ruoyi-vue-pro/pull/1019 |
| | | // 情况一:有 JsonFormat 自定义注解,则使用它 |
| | | String fieldName = gen.streamWriteContext().currentName(); |
| | | if (fieldName != null) { |
| | | Object currentValue = gen.currentValue(); |
| | |
| | | Class<?> clazz = currentValue.getClass(); |
| | | Map<String, Field> fieldMap = FIELD_CACHE.computeIfAbsent(clazz, this::buildFieldMap); |
| | | Field field = fieldMap.get(fieldName); |
| | | // 进一步修复:https://gitee.com/zhijiantianya/ruoyi-vue-pro/pulls/1480 |
| | | if (field != null && field.isAnnotationPresent(JsonFormat.class)) { |
| | | JsonFormat jsonFormat = field.getAnnotation(JsonFormat.class); |
| | | try { |
| | | DateTimeFormatter formatter = DateTimeFormatter.ofPattern(jsonFormat.pattern()); |
| | | gen.writeString(formatter.format(value)); |
| | | // 若指定输出为数字(时间戳),则按原始方式处理 |
| | | if (jsonFormat.shape() == JsonFormat.Shape.NUMBER) { |
| | | gen.writeNumber(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); |
| | | return; |
| | | } catch (Exception ex) { |
| | | log.warn("[serialize][({}#{}) 使用 JsonFormat pattern 失败,尝试使用默认的 Long 时间戳]", |
| | | clazz.getName(), fieldName, ex); |
| | | } |
| | | // 若指定了自定义 pattern,则使用 pattern 格式化 |
| | | if (StrUtil.isNotEmpty(jsonFormat.pattern())) { |
| | | try { |
| | | DateTimeFormatter formatter = DateTimeFormatter.ofPattern(jsonFormat.pattern()); |
| | | gen.writeString(formatter.format(value)); |
| | | return; |
| | | } catch (Exception ex) { |
| | | log.warn("[serialize][({}#{}) 使用 JsonFormat pattern 失败,尝试使用默认格式]", |
| | | clazz.getName(), fieldName, ex); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | // 情况二:默认将 LocalDateTime 对象,转换为 Long 时间戳 |
| | | gen.writeNumber(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); |
| | | // 情况二:默认格式化为 yyyy-MM-dd HH:mm:ss 字符串 |
| | | gen.writeString(DEFAULT_FORMATTER.format(value)); |
| | | } |
| | | |
| | | /** |