HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

JAXB Convert Object to JSON Example

By Lokesh Gupta | Filed Under: JAXB

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.

Happy Learning !!

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

JAXB Tutorial

  • JAXB – Annotations
  • JAXB – @XmlRootElement
  • JAXB – @XmlElementWrapper
  • JAXB – Marshaller
  • JAXB – Unmarshaller
  • JAXB – Convert XML to Java Object
  • JAXB – Convert JSON to Java Object
  • JAXB – Convert Java Object to XML
  • JAXB – Convert Java Object to JSON
  • JAXB – Map
  • JAXB – List and Set
  • JAXB – Generate Schema
  • JAXB – Schema Validation
  • JAXB – JAXBException
  • JAXB – IllegalAnnotationExceptions
  • JAXB – Marshal without @XmlRootElement
  • JAXB – Unmarshal without @XmlRootElement

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap