Skip to content
Advertisement

JAXB Mapping to JSON

I have written a JAX-RS (Jersey) REST Service, which accepts XML messages of ONIX XML format. Generally, I have generated all the required classes for JAXB binding from the given schema with xjc. There are more than 500 classes overall and I cannot modify them.

Now, when I have a JAXB-mapped object, I need to store it to the database. I work with mongoDb, so the message format should be JSON. I tried to use Jackson with JAXB module to convert JAXB-object into JSON, which works pretty fine with storing the data. But when I try to convert the JSON back into the JAXB object, it throws an exception connected somehow with the JAXBElement. In google I found out that the JAXBElement is not supported in Jackson and I have to work around this issue. But I cant do it because I cannot modify JAXB-generated classes.

Is there a way to map JAXB Objects into JSON with some other means, but which will follow the whole JAXB specification so that I have no problems in the future converting from JSON to the JAXB object and visa vera?

Advertisement

Answer

Note: I’m the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

If you can’t do it with Jackson, you use case will work with MOXy.

Java Model

Foo

Here is a sample class that contains a field of type JAXBElement.

JavaScript

Bar

JavaScript

ObjectFactory

JavaScript

Standalone Demo Code

Below is some demo code you can run in Java SE to see that everything works:

Demo

JavaScript

input.json/Output

JavaScript

Running with JAX-RS

The following links will help you leverage MOXy in a JAX-RS service:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement