简体   繁体   English

如何使 fastxml ObjectMapper 与 codehaus 注释一起使用

[英]How to make fasterxml ObjectMapper work with codehaus annotations

I'm using the ObjectMapper class from the fasterxml package ( com.fasterxml.jackson.databind.ObjectMapper ) to serialize some POJOs.我正在使用fasterxml包( com.fasterxml.jackson.databind.ObjectMapper )中的ObjectMapper类来序列化一些POJO。

The problem I'm facing is that all the annotations in the POJOs are from the older codehaus library.我面临的问题是 POJO 中的所有注释都来自较旧的 codehaus 库。 The fasterxml ObjectMapper is not recognizing the codehaus jackson annotations. fasterxml ObjectMapper无法识别 codehaus jackson 注释。
One possible solution is to update the annotations in the POJO to fasterxml , but the POJOs are provided by a third party, hence I cannot modify it.一种可能的解决方案是将 POJO 中的注释更新为fasterxml ,但 POJO 由第三方提供,因此我无法对其进行修改。

How can I solve this problem?我该如何解决这个问题?

You can provide your own AnnotationIntrospector to process old annotation.您可以提供自己的AnnotationIntrospector来处理旧注释。

ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new MyAnnotationIntrospector());

You can also checkout the jackson-legacy-introspector listed on the jackson github.您还可以查看 jackson github 上列出的jackson-legacy-introspector It's an existing implementation of AnnotationIntrospector for old annotations.它是旧注释的 AnnotationIntrospector 的现有实现。

If you can use workaround with inheritance如果您可以使用继承的解决方法

// Original class doesn't need to be modified
class Customer {
     @org.codehaus.jackson.annotate.JsonProperty("first_name")
     String firstName;
}

class CustomerWrapper extends Customer {
     @com.fasterxml.jackson.annotation.JsonProperty("first_name")
     String firstName;
}

And in code use CustomerWrapper class which will be serialized correctly并在代码中使用 CustomerWrapper 类,它将被正确序列化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM