JAXB JSON Example
In this example we shall show you how to make use of JAXB-JSON. JAXB
is a java architecture for XML binding is an efficient technology to convert XML to and from Java Object. EclipseLink JAXB (MOXy)
is one of JAXB
implementation which is mostly used to create java classes from XML or JSON. In Java JAXB
provides two general purpose implementation.
Marshalling
– It Converts a Java object into XML or JSON.Unmarshalling
– It Converts XML or JSON into a Java Object.
Now, We will demonstrate the native object-to-JSON binding MOXy JAXB introduced in EclipseLink 2.4. With MOXy as your JAXB provider you can produce/consume JSON using the standard JAXB APIs (available in Java SE 6) without adding any compile time dependencies.
Example:
1. MOXy Dependency:
<dependencies> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.moxy</artifactId> <version>2.5.2</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.2.11</version> </dependency> </dependencies>
2. Simple Pojo:
Create an employee object, initialized with some values, it will be converted to / from JSON.
Employee.java:
package com.jcg.jaxb.json; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; /** * @author ashraf_sarhan * */ @XmlRootElement public class Employee { private int id; private String name; private List skills; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getSkills() { return skills; } public void setSkills(List skills) { this.skills = skills; } }
3. Marshal Java Object to JSON:
Create a JaxBContext using the Employee class then convert the “employee” Java object into JSON formatted string using Marshaller object with following three properties:
MEDIA_TYPE
– Determine the produced output media type (JSON, XML).JSON_INCLUDE_ROOT
– Flag to determine whether you want to include the JSON root element in the produced output or not.JAXB_FORMATTED_OUTPUT
– Flag to determine whether you want to format the produced output or not.
MarshallerDemo.java:
package com.jcg.jaxb.json; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.eclipse.persistence.jaxb.MarshallerProperties; /** * @author ashraf_sarhan * */ public class MarshallerDemo { /** * @param args * @throws JAXBException * Marshaller POJO to JSON using EclipseLink MOXy */ public static void main(String[] args) throws JAXBException { // Creating a new employee pojo object with data Employee employee = new Employee(); employee.setId(1); employee.setName("Ashraf"); List skills = new ArrayList(); skills.add("java"); skills.add("sql"); employee.setSkills(skills); // Create a JaxBContext JAXBContext jc = JAXBContext.newInstance(Employee.class); // Create the Marshaller Object using the JaxB Context Marshaller marshaller = jc.createMarshaller(); // Set the Marshaller media type to JSON or XML marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json"); // Set it to true if you need to include the JSON root element in the JSON output marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true); // Set it to true if you need the JSON output to formatted marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // Marshal the employee object to JSON and print the output to console marshaller.marshal(employee, System.out); } }
Output:
{ "employee" : { "id" : 1, "name" : "Ashraf", "skills" : [ "java", "sql" ] } }
4. Unmarshal JSON to Java Object:
Create a JaxBContext using the Employee class then read the provided JSON string and convert it back to the “employee” Java object using Unmarshaller object with following two properties:
MEDIA_TYPE
– Determine the provided input media type (JSON, XML).JSON_INCLUDE_ROOT
– Flag to determine whether you want to include the JSON root element in the provided input or not.
UnmarshallerDemo.java:
package com.jcg.jaxb.json; import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import org.apache.commons.lang3.StringUtils; import org.eclipse.persistence.jaxb.UnmarshallerProperties; /** * @author ashraf_sarhan * */ public class UnmarshallerDemo { /** * @param args * @throws JAXBException * Unmarshaller JSON to POJO using EclipseLink MOXy */ public static void main(String[] args) throws JAXBException { // Create a JaxBContext JAXBContext jc = JAXBContext.newInstance(Employee.class); // Create the Unmarshaller Object using the JaxB Context Unmarshaller unmarshaller = jc.createUnmarshaller(); // Set the Unmarshaller media type to JSON or XML unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); // Set it to true if you need to include the JSON root element in the // JSON input unmarshaller .setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, true); // Create the StreamSource by creating StringReader using the JSON input StreamSource json = new StreamSource( new StringReader( "{\"employee\":{\"id\":1,\"name\":\"Ashraf\",\"skills\":[\"java\",\"sql\"]}}")); // Getting the employee pojo again from the json Employee employee = unmarshaller.unmarshal(json, Employee.class) .getValue(); // Print the employee data to console System.out.println("Employee Id: " + employee.getId()); System.out.println("\nEmployee Name: " + employee.getName()); System.out.println("\nEmployee Skills: " + StringUtils.join(employee.getSkills(), ',')); } }
Output:
Employee Id: 1 Employee Name: Ashraf Employee Skills: java,sql
Tip
Specify MOXy as the JAXB Provider (jaxb.properties)
To configure MOXy as your JAXB provider simply add a file named jaxb.properties in the same package as your domain model with the following entry:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
5. Download the Source Code of this example:
This was an example of how to use JAXB-JSON to marshal and unmarshal java POJO using the native Object to JSON binding of MOXy JAXB.
You can download the full source code of this example here: JAXB-JSON Example Code
I am getting while implementing MarshalDemo.java class
Exception in thread “main” java.lang.NoClassDefFoundError: org/eclipse/persistence/internal/oxm/mappings/VariableXPathObjectMapping
at org.eclipse.persistence.jaxb.compiler.Generator.<init>(Generator.java:145)
at org.eclipse.persistence.jaxb.JAXBContext$TypeMappingInfoInput.createContextState(JAXBContext.java:1088)
at org.eclipse.persistence.jaxb.JAXBContext.<init>(JAXBContext.java:189)
at org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(JAXBContextFactory.java:165)
at org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(JAXBContextFactory.java:152)
at org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(JAXBContextFactory.java:112)
at org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(JAXBContextFactory.java:102)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.find(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at com.test.Test2.main(Test2.java:24)
Caused by: java.lang.ClassNotFoundException: org.eclipse.persistence.internal.oxm.mappings.VariableXPathObjectMapping
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 17 more