Convert json to java object example with moxy and jaxb

Java example to convert JSON to Java Object. You can unmarshal JSON String to Object or JSON file to Object, both. This example uses MOXy along with JAXB to unmarshal JSON to Java object. 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. Convert JSON File to Java Object

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

3. Convert JSON file to Object

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

package com.howtodoinjava.demo;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.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 JSON file to read is:

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

4. Convert JSON String to Java Object

You can get the JSON in String form and then populate to Java objects directly.

package com.howtodoinjava.demo;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.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 jsonString = "{\"employee\":{\"department\":{\"id\":101,\"name\":\"IT\"},
							\"firstName\":\"Lokesh\",\"id\":1,\"lastName\":\"Gupta\"}}";
		jaxbJsonStringToObject(jsonString);
	}
	
	private static void jaxbJsonStringToObject(String jsonString) 
	{
		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(new StringReader(jsonString));
			
			System.out.println(employee);
		}
		catch (JAXBException e) 
		{
			e.printStackTrace();
		}
	}
}

Program Output:

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

5. Convert Java Object to JSON

Example of converting Java 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

Drop me your questions related to marshalling and unmarshalling json in java example in comments section.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.