1
|
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group,
Below is how this can be done if you are using MOXy as your JAXB provider.
JAVA MODEL
Customer
PhoneNumber
jaxb.properties
To specify MOXy as your JAXB provider you need to include a file called
jaxb.properties in 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 CODE
input.xml
|
Demo
In the demo code below we will use the same JAXB metadata to convert an XML document to Java objects, and then convert those objects back to JSON. With MOXy you can specify JSON output by setting a property on the
Marshaller
.import java.io.File;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum15357366/input.xml");
Customer customer = (Customer) unmarshaller.unmarshal(xml)
;
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
marshaller.marshal(customer, System.out);
}
}
JSON Output
Below is the JSON output. Note how there are no indicators corresponding to namespaces or XML attributes. Also note the collection of size one was correctly represented as a JSON array (a problem with some other approaches).
{
"id" : 123,
"firstName" : "Jane",
"lastName" : null,
"phoneNumbers" : [ {
"type" : "work",
"value" : "555-1111"
} ]
}
pom.xml
from an example that I have hosted on GitHub that you can use as a guide: github.com/bdoughan/blog20110819/blob/master/pom.xml – Blaise Doughan Mar 12 at 11:27