Jackson Java Spring

Jackson Supporting JAXB Annotations in Spring

Spring Framework by default is using JAXB for binding XML schemas and Java objects. When we generate our Java representations from XML schema using JAXB, our POJOs will contain JAXB annotations like @XmlRootElement, @XmlElement, etc. If we want Spring to use Jackson with our POJOs generated by JAXB, we will have to add following dependency to our pom.xml file:

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
  <version>2.9.0</version>
</dependency>

It is also recommended to add faster XML parser support:

<dependency>
  <groupId>org.codehaus.woodstox</groupId>
  <artifactId>woodstox-core-asl</artifactId>
  <version>4.4.1</version>
</dependency>

From now on, Spring will use Jackson for serializing POJOs as XML and deserializing POJOs from XML. Unfortunately, JAXB annotations won’t be supported by Jackson by default. Let’s add following dependency which will enable Jackson to understand JAXB annotations:

<dependency>
  <groupId>com.fasterxml.jackson.module</groupId>
  <artifactId>jackson-module-jaxb-annotations</artifactId>
  <version>2.4.0</version>
</dependency>

Now it’s the time for gluing everything together by adding proper configuration using Spring @Configuration class.

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {
  
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        final MappingJackson2XmlHttpMessageConverter conv = new MappingJackson2XmlHttpMessageConverter();
        conv.setObjectMapper(createXmlMapper());
        converters.add(conv);
        converters.add(new MappingJackson2HttpMessageConverter());
    }
      
    private XmlMapper createXmlMapper() {
        final XmlMapper mapper = new XmlMapper();
        mapper.registerModule(new JaxbAnnotationModule());
        return mapper;
    }
}

In our implementation of configureMessageConverters() method from WebMvcConfigurer interface we will add MappingJackson2XmlHttpMessageConverter with XmlMapper which has JaxbAnnotationModule registered. If we also want serialization of POJOs as JSON and deserialization POJOs from JSON, we will have to add also MappingJackson2HttpMessageConverter.

For more information please visit: