JAXB for JSON using JACKSON

In my application, JAXB output generates:

this.marshalOut(jaxb_Object, fileOutputStream);

this is a method call for spring Marshallers matching XML objects that generate XML files. Now I also like to generate JSON files after this line. Anyone have the idea of ​​generating JSON output using JAXB input.

I found this sample 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);

setAnnotationIntrospector out of date, is there any other way to solve this problem?

+5
source share
5 answers

The following steps (and do not use legacy constructors):

ObjectMapper mapper = new ObjectMapper();

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

mapper.setAnnotationIntrospector(introspector);

In particular, this line

new JaxbAnnotationIntrospector(mapper.getTypeFactory());

uses a constructor that does not contain outdated information. I tested this and it successfully handles JAXB annotations (e.g. @XmlTransient, in my case).

+4
source

The correct solution for me was:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector());
+2
source

You can use jackson-module-jaxb-annotations as indicated in the document, you can register a module JaxbAnnotationModule:

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

By doing this, you can now use the JAXB annotation and Jackson annotation.

+2
source

According to 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

Have you checked the method withAnnotationIntrospector(AnnotationIntrospector ai)to see how it works or is not useful in your case?

0
source

All Articles