Home » Java » JAXB to JSON using JACKSON

JAXB to JSON using JACKSON

Posted by: admin December 28, 2021 Leave a comment

Questions:

In my application the JAXB output generates like:

this.marshalOut(jaxb_Object, fileOutputStream);

this is method call to the spring Object XML Mapping Marshallers that generate XML files. Now, I also like to generate JSON files after this line. Any one have idea about generating JSON output using JAXB input.

I found this example code online:

ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
// make deserializer use JAXB annotations (only)
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
// make serializer use JAXB annotations (only)
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
mapper.writeValue( outputStream, jaxb_object);

The setAnnotationIntrospector is deprecated, is there any other way of solving this problem?

Answers:

The following works (and does not use any deprecated constructors) :

ObjectMapper mapper = new ObjectMapper();

AnnotationIntrospector introspector =
    new JaxbAnnotationIntrospector(mapper.getTypeFactory());   

mapper.setAnnotationIntrospector(introspector);

Specifically, this line

new JaxbAnnotationIntrospector(mapper.getTypeFactory());

uses a non-deprecated constructor. I’ve tested this and it successfully processes JAXB Annotations (such as @XmlTransient, in my case).

###

You can use jackson-module-jaxb-annotations as stated in the doc you can register a JaxbAnnotationModule module:

JaxbAnnotationModule module = new JaxbAnnotationModule();
// configure as necessary
objectMapper.registerModule(module);

Doing so you can now use both JAXB annotation and Jackson native annotation.

###

If you update Jackson to 2.0 it is not deprecated:

http://fasterxml.github.com/jackson-databind/javadoc/2.0.0/com/fasterxml/jackson/databind/ObjectMapper.html

You can see my configuration here (Spring):

Registrer MappingJackson2HttpMessageConverter in Spring 3.1.2 with JAXB annotations

###

The correct solution for me was:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector());

###

According to the Jackson javadoc:

setAnnotationIntrospector

@Deprecated
public final void setAnnotationIntrospector(AnnotationIntrospector ai)

    Deprecated. Since 1.8, use either withAnnotationIntrospector(AnnotationIntrospector) or Module API instead

    Method for replacing existing annotation introspector(s) with specified introspector. Since this method modifies state of configuration object directly, its use is not recommended

Did you check the method withAnnotationIntrospector(AnnotationIntrospector ai) to see wheter or not it’s useful in your case?