SpringBoot 自定义JsonSerializer使用HttpServletRequest

需求:时间格式转换,将 LocalDateTime 转换成 时间戳 格式,但是需要兼容老版本WEB/APP,需要使用 Header 中的 Api-Version 字段,进行版本判断。

1.先看一下错误代码(此时,request=null)

@Component
public class LocalDateTime2TimestampSerializer extends JsonSerializer<LocalDateTime> {

    @Resource
    private HttpServletRequest request;

    @Override
    public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        String apiVersion = request.getHeader("Api-Version");
        if (StringUtils.isBlank(apiVersion) || VersionUtils.afterVersion(apiVersion, "v1.2.23")) {
            //将LocalDateTime格式转成时间戳返回前端
            if (localDateTime != null) {
                jsonGenerator.writeNumber(DateUtils.LocalDateTime2timestamp(localDateTime));
                return;
            }
        }
        if (localDateTime != null) {
            jsonGenerator.writeString(localDateTime.format(DateUtils.yyyyMMddHHmmss_LocalDate));
        }
    }
}

2.将代码进行一下修改(换了另一种注入方式)

@Component
@NoArgsConstructor
public class LocalDateTime2TimestampSerializer extends JsonSerializer<LocalDateTime> {

    private static HttpServletRequest request;

    @Autowired//需要使用构造器注入,直接 属性注入,request=null
    public LocalDateTime2TimestampSerializer(HttpServletRequest request) {
        LocalDateTime2TimestampSerializer.request = request;
    }

    @Override
    public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        String apiVersion = request.getHeader("Api-Version");
        if (StringUtils.isBlank(apiVersion) || VersionUtils.afterVersion(apiVersion, "v1.2.23")) {
            //将LocalDateTime格式转成时间戳返回前端
            if (localDateTime != null) {
                jsonGenerator.writeNumber(DateUtils.LocalDateTime2timestamp(localDateTime));
                return;
            }
        }
        if (localDateTime != null) {
            jsonGenerator.writeString(localDateTime.format(DateUtils.yyyyMMddHHmmss_LocalDate));
        }
    }
}

最后,原因未知。找时间看下底层源码,先记录一下。如果有大神路过,希望可以指点一下我。万分感谢。

posted @ 2022-09-08 13:04  cchilei  阅读(267)  评论(0编辑  收藏  举报