Eclipse MOXy: Unmarshal JSON to Java Object

This JAXB tutorial demonstrates using MOXy to convert JSON String to Java Object. MOXy implements JAXB, allowing developers to provide their mapping information through annotations and provide many rich features that JAXB doesn’t provide by default.

EclipseLink MOXy includes many advanced mappings that allow us to handle complex XML structures without having to mirror the schema in the Java class model.

1. MOXy Dependency

Include the latest version of MOXy to project runtime.

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>4.0.2</version>
</dependency>

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

2. Setup

2.1. Add JAXB Annotations

If not done, start with adding the JAXB annotations in the class. This example uses Employee and Department classes.

@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 we get the instance of JAXBContext, JAXB checks for jaxb.properties file and constructs the context. Here, we can inject the JAXBContextFactory from MOXy library.

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

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

3. Unmarshalling JSON File to Java Object

Now use javax.xml.bind.UnMarshaller class to convert JSON to POJO.

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

public class JaxbExample
{
	public static void main(String[] args)
	{
		String fileName = "employee.json";
		jaxbJsonToObject(fileName);
	}

	private static void jaxbJsonToObject(String fileName) {
		File xmlFile = new File(fileName);

		JAXBContext jaxbContext;
		try
		{
			jaxbContext = JAXBContext.newInstance(Employee.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

			//Set JSON type
			jaxbUnmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
			jaxbUnmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, true);

			Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile);

			System.out.println(employee);
		}
		catch (JAXBException e)
		{
			e.printStackTrace();
		}
	}
}

Program Output:

Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

Where the JSON file is:

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

4. Convert JSON String to Java Object

We can get the JSON in String and then populate it to Java objects directly.

String jsonString = "{\"employee\":{\"department\":{\"id\":101,\"name\":\"IT\"},
							\"firstName\":\"Lokesh\",\"id\":1,\"lastName\":\"Gupta\"}}";

Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new StringReader(jsonString));

Program Output:

Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

Drop me your questions related to unmarshalling JSON to Java objects in the comments section.

Happy Learning !!

Comments

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

Dark Mode

Dark Mode