Using JAXB annotations with Jackson

Although JSON is not XML and XML is not JSON, but the process for (de)serializing Java objects to/from JSON has many similarities to the process of (de)serializing Java objects to/from XML. So a significant part of the JAXB metadata is applicable to (de)serializing JSON data.

As a result, with Jackson 1.1 (and later) it is possible to use annotations defined by JAXB API. These annotations are found from JDK package javax.xml.bind.annotation

Changes with Jackson 2.0

With Jackson 2.0, functionality has been moved to a separate Github project, jackson-module-jaxb-annotations. Functionality has not been changed, and instructions below should work as well. In future some of the documentation will be moving to the project pages as well.

Enabling JAXB annotation support

By default, only core Jackson annotations are used for configuring data binding aspects. To enable JAXB annotation support, you need to:

Registering JAXB annotation introspector

Annotation introspector to use for serialization process is configured separately for serialization and deserialization purposes; for example:

    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    // make deserializer use JAXB annotations (only)
    // make serializer use JAXB annotations (only)

But you do not have to choose between Jackson and JAXB annotations: it is possible and easy to use both. You just have to decide which should have precedence, in case both would define a configuration property. With that, you can construct an annotation introspector. For example: to use JAXB introspector as a fallback, you would do:

    AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
    AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
    AnnotationIntrospector pair = new AnnotationIntrospector.Pair(primaryIntrospector, secondaryIntropsector);

and then configure ObjectMapper as shown above.

Supported JAXB annotations

The following JAXB annotations are honored:

Annotations that may be supported for XML generation

Many annotations that have no JSON counterpart can be useful when dealing with XML (using Jackson XML dataformat module).

These annotations include:

Not(-yet)-Supported JAXB annotations

Following annotations are not currently supported:

JAXB annotations very unlikely to ever be supported

Following annotations refer to concepts that do not exist with JSON, and thus are highly unlikely to be supported for JSON production. They could theoretically be supported if Jackson was to produce XML


JacksonJAXBAnnotations (last edited 2012-08-14 20:03:47 by TatuSaloranta)

Copyright ©2009 FasterXML, LLC