How to add Jackson annotations to POJO generated f

2019-02-27 18:30发布

问题:

I'm generating POJOs from XSDs using JAXB. And I'm using Jersey/Jackson to serialize the POJOs to JSONs. For the whole project, I've created an ObjectMapper that has Inclusion.NON_NULL set. But for one particular serialization class, I want to include null values. I know, I have to use Inclusion.ALWAYS on the POJO to override the ObjectMapper, but the POJO I'm using is generated from XSDs.

Is there a way to add this Jackson's annotation @JsonSerialize(include=Inclusion.ALWAYS) to that one particular POJO during marshalling?

http://pastebin.com/a2Gvw19U

回答1:

If you just want to add one annotation, consider using my JAXB2 Annotate Plugin. See, for instance, this example, specifically this bindings file.

In your case the bindings will look something like:

<jaxb:bindings node="xs:complexType[@name='myPOJO']">
    <annox:annotate>
        @org.codehaus.jackson.map.annotate.JsonSerialize
            (include=org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion.ALWAYS)
    </annox:annotate>
</jaxb:bindings>

(Not tested, just a sketch.)

Few hints:

  • Syntax is Java, but you have to use fully qualified class names.
  • Jackson JAR must be present in the XJC classpath, otherwise your annotations won't be found.

SO disclaimer: I am the author of the mentioned plugin.