bind

JAXB JSON Example

Photo of Ashraf SarhanAshraf SarhanSeptember 8th, 2014Last Updated: September 5th, 2014
1 3,404 3 minutes read

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 ofJAXB implementation which is mostly used to create java classes from XML or JSON. In JavaJAXB 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 *  */@XmlRootElementpublic 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 dataEmployee employee = new Employee();employee.setId(1);employee.setName("Ashraf");List skills = new ArrayList();skills.add("java");skills.add("sql");employee.setSkills(skills);// Create a JaxBContextJAXBContext jc = JAXBContext.newInstance(Employee.class);// Create the Marshaller Object using the JaxB ContextMarshaller marshaller = jc.createMarshaller();// Set the Marshaller media type to JSON or XMLmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE,"application/json");// Set it to true if you need to include the JSON root element in the JSON outputmarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);// Set it to true if you need the JSON output to formattedmarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// Marshal the employee object to JSON and print the output to consolemarshaller.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 JaxBContextJAXBContext jc = JAXBContext.newInstance(Employee.class);// Create the Unmarshaller Object using the JaxB ContextUnmarshaller unmarshaller = jc.createUnmarshaller();// Set the Unmarshaller media type to JSON or XMLunmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE,"application/json");// Set it to true if you need to include the JSON root element in the// JSON inputunmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, true);// Create the StreamSource by creating StringReader using the JSON inputStreamSource json = new StreamSource(new StringReader("{\"employee\":{\"id\":1,\"name\":\"Ashraf\",\"skills\":[\"java\",\"sql\"]}}"));// Getting the employee pojo again from the jsonEmployee employee = unmarshaller.unmarshal(json, Employee.class).getValue();// Print the employee data to consoleSystem.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: 1Employee Name: AshrafEmployee 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 ofMOXy JAXB.

Download
You can download the full source code of this example here:JAXB-JSON Example Code
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Ashraf SarhanAshraf SarhanSeptember 8th, 2014Last Updated: September 5th, 2014
1 3,404 3 minutes read
Photo of Ashraf Sarhan

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.