I have to use a lib that only gives me a JAXBContext to marshall and unmarshall XML data to Java objects. Also I don't ever see XML: Only the JAXB objects are passed to me. What I now need is a conversion of those objects not to XML, but to JSON.
Is there a way to create a marshaller from the given JAXBContext that can be used to generate JSON output?
The situation is that I'm not only transforming data. I also have logic that acts on the Java objects between XML and JSON (and manipulates the data). Also it's a two-way transformation. The JAXBContext is the information I have about the transformation between XML and Java objects - My intention was to reuse this context information for not having to implement a second transformation with a second technology different to JAXB. The JAXBContext (and its Java objects) already have the information about the XML structure; The automated recognition of that structure by JAXB is the time-saving reason for using it.
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.
You can see the link above for all the supported annotations. The maven artifact you'll need is
jackson-module-jaxb-annotations
- Note this artifact has dependencies onjackson-core
andjackson-databind
. So if you're not using maven, then you will need to make sure to download these artifacts alsoSimple Exmaple:
JAXB Class
XML
Test
Result
Update
Also see this post. It looks like MOXy also offers this support.