Home » Core Java » xml » bind » JAXB JSON Example

About 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.

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.

Download
You can download the full source code of this example here: JAXB-JSON Example Code
0 0 vote
Article Rating

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

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 ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest
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.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x