Its quite easy to convert a java object to XML by using Marshaller. But I need to convert a java object to JSON by using marshaller alone. I know its good to use gson or Xstream like things., but I need to do using Marshaller.How to achieve it?
Thanks in advance.
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
.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).
JsonMarshaller is a Java 1.5 library that allows marshalling and unmarshalling of JSON objects to and from Java objects. This project's goal is above all ease of use, transparency and static type safety. Example
If you have the following Java class:
JAVA:
and you created a new Book() and populated it with info it could marshal too: