fastjson 怎么样全局配置将 Date 和 LocalDateTime 序列化为毫秒级的时间戳?

cygmwpex  于 2022-10-21  发布在  其他
关注(0)|答案(1)|浏览(471)

使用的版本

1.2.83

0.需求

全局配置 DateLocalDateTime 序列化为毫秒级的时间戳

1.不设置 SerializerFeature.WriteDateUseDateFormat

Date 类就直接是转为时间戳
但是 LocalDateTimeyyyy-MM-dd HH:mm:ss格式

2.于是我全局配置了 WriteDateUseDateFormatfastJsonConfig.setDateFormat("millis") ;

LocalDateTime 能正确序列化为 时间戳,但是 Date 类型又不工作了

我发现是 com.alibaba.fastjson.serializer.DateCodec 120行出错了

if (out.isEnabled(SerializerFeature.WriteDateUseDateFormat)) {
          DateFormat format = serializer.getDateFormat();
          if (format == null) {
              // 如果是通过FastJsonConfig进行设置,优先从FastJsonConfig获取
              String dateFormatPattern = serializer.getFastJsonConfigDateFormatPattern();
              if(dateFormatPattern == null) {
                  dateFormatPattern = JSON.DEFFAULT_DATE_FORMAT;
              }

120行--》format = new SimpleDateFormat(dateFormatPattern, serializer.locale);
              format.setTimeZone(serializer.timeZone);
          }
          String text = format.format(date);
          out.writeString(text);
          return;
      }

119行这里是不是应该也加两句类似前面 第99行开始 的 时间戳判断逻辑?

if ("unixtime".equals(dateFormatPattern)) {
            long seconds = date.getTime() / 1000;
            out.writeLong(seconds);
            return;
        }

        if ("millis".equals(dateFormatPattern)) {
            long millis = date.getTime();
            out.writeLong(millis);
            return;
        }

3.打开方式不对,应该用别的方式实现我这个需求?

相关问题