@JsonSerialize 注解失效

1,168 阅读1分钟

需求背景

在项目中有一个需求,将老项目中现有的时间格式的数据,转成时间戳格式返回前端。这时,我就想到了Jackson的JsonSerializer,写一个自定义处理类就行了呀。

自定义处理类

@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 {
        //无需兼容,全部按时间戳返回
        List<String> filterList = List.of("xxxxx", "xxxxxx");

        String apiVersion = request.getHeader("Api-Version");
        String requestURI = request.getRequestURI();
        if (StringUtils.isBlank(apiVersion) || VersionUtils.afterVersion(apiVersion, "v1.2.23")
                || filterList.contains(requestURI)) {
            //将LocalDateTime格式转成时间戳返回前端
            if (localDateTime != null) {
                jsonGenerator.writeNumber(DateUtils.LocalDateTime2timestamp(localDateTime));
                return;
            }
        }
        if (localDateTime != null) {
            jsonGenerator.writeString(localDateTime.format(DateUtils.yyyyMMddHHmmss_LocalDate));
        }
    }
}

返回前端的VO

@Data
public class AppMsgListResp {
    private Integer type;
    private Long count;
    @JsonSerialize(using = LocalDateTime2TimestampSerializer.class)
    private LocalDateTime createTime;
    private String templateContent;
    private String typeStr;
    private String icon;
}

出现问题

发现时间返回错误了

image.png

王德发?这是什么鬼,看着代码啥的都没问题啊。打断点调试了一下,发现没有进自定义处理类LocalDateTime2TimestampSerializer。最后发现,是因为,以前老代码在切面使用了JsonObject处理了一下对象。

image.png

唉,那只能在现有的情况进行处理,将对象使用Jaskson转换成String,在进行JsonObject转换。

image.png

附(fastjson issue):github.com/alibaba/fas…

修订后的截图

image.png

总结

当前项目中同时有FastJsonJackson,配置的时候是使用fastjson,当你使用jackson的注解就不起作用。