JAXB Convert Object to JSON Example

Java example to convert Java objects to JSON string or write JSON to file. This example uses MOXy along with JAXB to marshal Java object to JSON. MOXy implements JAXB allowing developers to provide their mapping information through annotations as well as provide many rich features which JAXB doesn’t provide by default.

1. MOXy Dependency

Include MOXy to project runtime.

<dependency>
	<groupId>org.eclipse.persistence</groupId>
	<artifactId>org.eclipse.persistence.moxy</artifactId>
	<version>2.5.2</version>
</dependency>

2. Java Object to JSON String

2.1. Add JAXB Annotations

@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private Integer id;
	private String firstName;
	private String lastName;
	private Department department;
	
	public Employee() {
		super();
	}

	//Setters and Getters
}
@XmlRootElement(name = "department")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Department implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	Integer id;
	String name;
	
	public Department() {
		super();
	}

	//Setters and Getters
}

2.2. Add jaxb.properties

When you get instance of JAXBContext, JAXB checks for jaxb.properties file and construct context. Here, you inject the JAXBContextFactory from MOXy library.

Place jaxb.properties file in same package where JAXB annotated classes are placed.

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

2.3. Convert Object to JSON

Now use javax.xml.bind.Marshaller class to convert object to json.

package com.howtodoinjava.demo;

import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import com.howtodoinjava.demo.model.Department;
import com.howtodoinjava.demo.model.Employee;

public class JaxbExample 
{
	public static void main(String[] args) 
	{
		Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT"));
		
		jaxbObjectToJSON(employee);
	}
	
	private static void jaxbObjectToJSON(Employee employee) 
	{
	    try 
	    {
	        JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
	        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

	        // To format JSON
	        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 
	        
	        //Set JSON type
	        jaxbMarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
	        jaxbMarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);

	        //Print JSON String to Console
	        StringWriter sw = new StringWriter();
	        jaxbMarshaller.marshal(employee, sw);
	        System.out.println(sw.toString());
	    } 
	    catch (JAXBException e) 
	    {
	        e.printStackTrace();
	    }
	}
}

Program output:

{
   "employee" : {
      "department" : {
         "id" : 101,
         "name" : "IT"
      },
      "firstName" : "Lokesh",
      "id" : 1,
      "lastName" : "Gupta"
   }
}

Read More : Convert Java Object to XML

3. Java Object to JSON File

Use above code with now output to json file.

package com.howtodoinjava.demo;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import com.howtodoinjava.demo.model.Department;
import com.howtodoinjava.demo.model.Employee;

public class JaxbExample 
{
	public static void main(String[] args) 
	{
		Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT"));
		
		jaxbObjectToJSON(employee);
	}
	
	private static void jaxbObjectToJSON(Employee employee) 
	{
	    try 
	    {
	        JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
	        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

	        // To format JSON
	        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 
	        
	        //Set JSON type
	        jaxbMarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
	        jaxbMarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);

	         //Store JSON to File
	        File file = new File("employee.json");
	        jaxbMarshaller.marshal(employee, file);
	    } 
	    catch (JAXBException e) 
	    {
	        e.printStackTrace();
	    }
	}
}

Program output:

{
   "employee" : {
      "department" : {
         "id" : 101,
         "name" : "IT"
      },
      "firstName" : "Lokesh",
      "id" : 1,
      "lastName" : "Gupta"
   }
}

Drop me your questions in comments section related to this convert java object to json example.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial