HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / JAXB / JAXB Convert Object to JSON Example

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

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

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
  • Jackson 2 – Object from/to JSON
  • Jackson – Object from/to json
  • Jackson – JSON from/to Map

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

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

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)