If your JAXB classes just use the basic annotations, you can take a look at JacksonJAXBAnnotations, allows Jackson mapper to recognize JAXN annotations. Four lines of code (in the simplest marshalling case) would be all you would need.
ObjectMapper mapper = new ObjectMapper();
JaxbAnnotationModule module = new JaxbAnnotationModule();
mapper.registerModule(module);
mapper.writeValue(System.out, yourJaxbObject);
You can see the link above for all the supported annotations. The maven artifact you'll need is
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.4.0</version>
</dependency>
- See the github for
jackson-module-jaxb-annotations
- Note this artifact has dependencies on jackson-core
and jackson-databind
. So if you're not using maven, then you will need to make sure to download these artifacts also
Simple Exmaple:
JAXB Class
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"hello",
"world"
})
@XmlRootElement(name = "root")
public class Root {
@XmlElement(required = true)
protected String hello;
@XmlElement(required = true)
protected String world;
// Getters and Setters
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
<hello>JAXB</hello>
<world>Jackson</world>
</root>
Test
public class TestJaxbJackson {
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
InputStream is = TestJaxbJackson.class.getResourceAsStream("test.xml");
Root root = (Root)unmarshaller.unmarshal(is);
System.out.println(root.getHello() + " " + root.getWorld());
ObjectMapper mapper = new ObjectMapper();
JaxbAnnotationModule module = new JaxbAnnotationModule();
mapper.registerModule(module);
mapper.writeValue(System.out, root);
}
}
Result
{"hello":"JAXB","world":"Jackson"}
Update
Also see this post. It looks like MOXy also offers this support.