I’m trying to write a code which can take either XML or JSON input and output JSON or XML respectively. I.e, if I give XML it should give back JSON, and if I give JSON it should give XML output.
I was told this is possible using Jackson API and JAXB Annotations. Can anyone help me out with this?
Note: I’m the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
Below is an example of how you can use MOXy’s JSON-binding to support this use case.
JAVA MODEL
Below is an example domain model annotated with JAXB metadata. The same metadata will be used for both the object-to-XML and object-to-JSON conversions.
Customer
PhoneNumber
XML INPUT
Below is the XML input that we will use. Note how the
xsi:nilattribute is used on thelastNameelement to indicate anullvalue. Also note how thephoneNumberselement has atypeattribute.DEMO CODE
jaxb.properties
To specify MOXy as your JAXB provider you need to include a file called
jaxb.propertiesin the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html):Demo
The following demo code will convert the XML to the domain model and then back to JSON.
JSON OUTPUT
Note how the
nullvalue for thelastNamekey is represented as proper JSON. Also note how thetypekey doesn’t contain any special indicator corresponding to it being an XML attribute in the XML representation.