UnMarshalling- How to convert XML to Java Objects using JAXB

HOME

This tutorial explains how to use JAXB (Java Architecture for XML Binding) to convert an XML document to Java Objects.

The previous tutorial has explained the conversion of Java Objects to XML.

As of Java 11, JAXB is not part of the JRE anymore, and you need to configure the relevant libraries via your dependency management system, for example, either Maven or Gradle.

Configure the Java compiler level to be at least 11 and add the JAXB dependencies to your pom file.

<?xml version="1.0" encoding="UTF-8"?>
 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
 
  <groupId>org.example</groupId>
  <artifactId>JAXBDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
 
  <name>JAXBDemo</name>
  <url>http://www.example.com</url>
 
  <properties>  
 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
  </dependency>
     
 <dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.3</version>
   </dependency>
 </dependencies>
    
</project>

Sample XML Structure

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<EmployeeDetails>
    <firstName>Terry</firstName>
    <lastName>Mathew</lastName>
    <gender>female</gender>
    <age>30</age>
    <maritalStatus>married</maritalStatus>
    <designation>Manager</designation>
    <contactNumber>+919999988822</contactNumber>
    <emailId>abc@test.com</emailId>
    <GrossSalary>75000.0</GrossSalary>
</EmployeeDetails>

Un-marshalling provides a client application the ability to convert XML data into JAXB-derived Java objects.

Let’s see the steps to convert XML document into java object.

  1. Create POJO Class
  2. Create the JAXBContext object
  3. Create the Unmarshaller objects
  4. Call the unmarshal method
  5. Use getter methods of POJO to access the data

Now, let us create the Java Objects (POJO) for the above XML.

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "EmployeeDetails")
@XmlAccessorType(XmlAccessType.FIELD)

//Define the order in which the fields are written in XML
@XmlType(propOrder = { "firstName", "lastName", "gender", "age", "maritalStatus", "designation", "contactNumber","emailId", "salary" })

public class Employee {

	private String firstName;
	private String lastName;
	private int age;

	@XmlElement(name = "GrossSalary")
	private double salary;
	private String designation;
	private String contactNumber;
	private String emailId;
	private String gender;
	private String maritalStatus;

	public Employee() {
		super();

	}

	// Getter and setter methods
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public String getContactNumber() {
		return contactNumber;
	}

	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getMaritalStatus() {
		return maritalStatus;
	}

	public void setMaritalStatus(String maritalStatus) {
		this.maritalStatus = maritalStatus;
	}

	@Override
	public String toString() {
		return "Employee [FirstName=" + firstName + ", LastName=" + lastName + ", Age=" + age + ", Salary=" + salary
				+ ", Designation=" + designation + ", ContactNumber=" + contactNumber + ", EmailId=" + emailId
				+ ", Gender=" + gender + ", MaritalStatus=" + maritalStatus + "]";
	}
}

Create the following test program for reading the XML file. The XML file is present under src/test/resources.

Let’s use JAXB Unmarshaller to unmarshal our JAXB_XML back to a Java object:

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.junit.Test;

public class JAXBDeserialization {
	
	@Test
	public void JAXBUnmarshalTest() {

		try {

			String userDir = System.getProperty("user.dir");
			File file = new File(userDir + "\\src\\test\\resources\\JAXB_XML.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);

			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			Employee employee = (Employee) jaxbUnmarshaller.unmarshal(file);

			System.out.println("FirstName: " + employee.getFirstName());
			System.out.println("LastName: " + employee.getLastName());
			System.out.println("Age: " + employee.getAge());
			System.out.println("Salary: " + employee.getSalary());
			System.out.println("Contact Number: " + employee.getContactNumber());
			System.out.println("Designation: " + employee.getDesignation());
			System.out.println("Gender: " + employee.getGender());
			System.out.println("EmailId: " + employee.getEmailId());
			System.out.println("MaritalStatus: " + employee.getMaritalStatus());

		} catch (JAXBException e) {
			e.printStackTrace();
		}

	}

	}

When we run the code above, we may check the console output to verify that we have successfully converted XML data into a Java object:

The output of the above program is

There is another simple way of unmarshalling the XML to Java Objects.

    @Test
	public void JAXBUnmarshalTest1() {

		try {

			String userDir = System.getProperty("user.dir");
			File file = new File(userDir + "\\src\\test\\resources\\JAXB_XML.xml");

			JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			Employee emp = (Employee) jaxbUnmarshaller.unmarshal(file);

			System.out.println(emp);

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

When we run the code above, we may check the console output to verify that we have successfully converted XML data into a Java object:

The output of the above program is

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Advertisement

Deserialization – How to convert XML to Java Objects using Jackson API

HOME

The previous tutorials have explained the conversion of Java Objects to XML using Jackson API. This tutorial explains parsing the XML document to Java objects using Jackson API.

To parse the XML, we will use the Jackson library. Use the latest Jackson library.

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.13.0</version>
</dependency>

Jackson allows us to read the contents of an XML file and deserialize the XML back into a Java object. In our example, we will read an XML document containing details about an Employee, and use Jackson to extract this data and use it to create Java objects containing the same information.

First, let us create an XML document matching our class to read from. Create deserialize.xml with the following contents:

<Employee>
  <firstName>Vibha</firstName>
  <lastName>Singh</lastName>
  <age>30</age>
  <salary>75000.0</salary>
  <designation>Manager</designation>
  <contactNumber>+919999988822</contactNumber>
  <emailId>abc@test.com</emailId>
  <gender>female</gender>
  <maritalStatus>married</maritalStatus>
</Employee>

Deserialization – It is the reverse of serializing. In this process, we will read the Serialized byte stream from the file and convert it back into the Class instance representation. Here, we are converting a XML to an Employee class object.

Let us add a deserializeFromXML() function to deserialize the XML file above into a Java object:

	@Test
	public void deserializeFromXML() {

		XmlMapper xmlMapper = new XmlMapper();
		String userDir = System.getProperty("user.dir");

		// Converting Employee XML to Employee class object
		try {
			Employee emp = xmlMapper.readValue(new File(userDir + "\\src\\test\\resources\\XMLExample.xml"),
					Employee.class);
			System.out.println("Deserialized data: ");
			System.out.println("First Name of employee : " + emp.getFirstName());
			System.out.println("Last Name of employee : " + emp.getLastName());
			System.out.println("Age of employee : " + emp.getAge());
			System.out.println("Salary of employee : " + emp.getSalary());
			System.out.println("Designation of employee : " + emp.getDesignation());
			System.out.println("Contact Number of employee : " + emp.getContactNumber());
			System.out.println("EmailId of employee : " + emp.getEmailId());
			System.out.println("Marital Status of employee : " + emp.getMaritalStatus());
			System.out.println("Gender of employee : " + emp.getGender());

		} catch (StreamReadException e) {
			e.printStackTrace();
		} catch (DatabindException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

The output of the above program is shown below:

Manipulating Nested Elements in XML

Let us enhance our XML file to add nested elements and loops, and modify our code to deserialize the following updated structure.

<Employees>
  <name>
    <firtsname>John</firtsname>
    <middlename>Dave</middlename>
    <lastname>William</lastname>
  </name>
  <contactdetails>
    <deskNumber>00-428507</deskNumber>
    <mobileNumber>+917823561231</mobileNumber>
    <emergencyDetails>
      <emergency_no1>+91 1212898920</emergency_no1>
      <emergency_no2>+91 9997722123</emergency_no2>
      <emergency_no3>+91 8023881245</emergency_no3>
    </emergencyDetails>
  </contactdetails>
  <age>30</age>
  <salary>75000.0</salary>
  <designation>Manager</designation>
  <emailId>abc@test.com</emailId>
  <gender>female</gender>
  <maritalStatus>married</maritalStatus>
</Employees>

There will be a slight change in the deserializeFromXML() method for the nested XML Structure.

   @Test
	public void deserializeFromXML() {

		XmlMapper xmlMapper = new XmlMapper();

		String userDir = System.getProperty("user.dir");

		// Converting Employee XML to Employee class object
		try {
			Employees employee2 = xmlMapper
					.readValue(new File(userDir + "\\src\\test\\resources\\NestedXMLExample.xml"), Employees.class);
			System.out.println("Deserialized data: ");
			System.out.println("First Name of employee : " + employee2.getName().getFirtsname());
			System.out.println("Middle Name of employee : " + employee2.getName().getMiddlename());
			System.out.println("Last Name of employee : " + employee2.getName().getLastname());
			System.out.println("Age of employee : " + employee2.getAge());
			System.out.println("Salary of employee : " + employee2.getSalary());
			System.out.println("Designation of employee : " + employee2.getDesignation());
			System.out.println("Desk Number of employee : " + employee2.getContactdetails().getDeskNumber());
			System.out.println("Mobile Number of employee : " + employee2.getContactdetails().getMobileNumber());
			System.out.println("Emergency Number1 of employee : "
					+ employee2.getContactdetails().getEmergencyDetails().getEmergency_no1());
			System.out.println("Emergency Number2 of employee : "
					+ employee2.getContactdetails().getEmergencyDetails().getEmergency_no2());
			System.out.println("Emergency Number3 of employee : "
					+ employee2.getContactdetails().getEmergencyDetails().getEmergency_no3());
			System.out.println("EmailId of employee : " + employee2.getEmailId());
			System.out.println("Gender of employee : " + employee2.getGender());
			System.out.println("Marital Status of employee : " + employee2.getMaritalStatus());

		} catch (StreamReadException e) {
			e.printStackTrace();
		} catch (DatabindException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

The output of the above program is shown below:

Here, you can see that when we need to serialize the nested attributes like Firstname, we have called the first Name class and then getFirstName().

System.out.println("First Name of employee : " + employee2.getName().getFirtsname());

To know about Serialization – Conversion of Java Objects to XML, you can refer to this tutorial – Serialization – How to convert Java Objects to XML using Jackson API.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Deserialization – How to create JSON Object to JAVA Object Using Gson API

HOME

In this tutorial, I will explain the conversion of JSON Object (payload) to JAVA Object. We will use Gson API for the same purpose.

Before going through this tutorial, spend some time understanding Serialization using Gson API.

We can parse the JSON or XML response into POJO classes. After parsing into POJO classes, we can easily get values from the response easily. This is called De-serialization. For this, we can use any JSON parser APIs. Here, we are going to use Gson API.

To start with, add the below dependency to the project.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

Sample JSON Payload

{
  "firstName" : "Vibha",
  "lastName" : "Singh",
  "age" : 30,
  "salary" : 75000.0,
  "designation" : "Manager",
  "contactNumber" : "+91999996712",
  "emailId" : "abc123@test.com"
}

Let us create a class called Employee with a field name exactly (case-sensitive) the same as node names in the above JSON string because with the default setting while parsing JSON object to Java object, it will look on getter setter methods of field names. 

public class Employee {

	// private variables or data members of POJO class
	private String firstName;
	private String lastName;
	private int age;
	private double salary;
	private String designation;
	private String contactNumber;
	private String emailId;

	// Getter and setter methods
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public String getContactNumber() {
		return contactNumber;
	}

	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

}

Gson class provides multiple overloaded fromJson() methods to achieve this. Below is a list of available methods:-

In the below test, I have mentioned the JSON Payload string in the test and used Gson API to deserialize the JSON payload to JAVA Object.

   @Test
	public void getDetailFromJson() {
		
		// De-serializing from JSON String
		String jsonString = "{\r\n" + "  \"firstName\": \"Tom\",\r\n" + "  \"lastName\": \"John\",\r\n"
				+ "  \"age\": 30,\r\n" + "  \"salary\": 50000.0,\r\n" + "  \"designation\": \"Lead\",\r\n"
				+ "  \"contactNumber\": \"+917642218922\",\r\n" + "  \"emailId\": \"abc@test.com\"\r\n" + "}";

		Gson gson = new Gson();
		// Pass JSON string and the POJO class
		Employee employee = gson.fromJson(jsonString, Employee.class);

		// Now use getter method to retrieve values
		System.out.println("Details of Employee is as below:-");
		System.out.println("First Name : " + employee.getFirstName());
		System.out.println("Last Name : " + employee.getLastName());
		System.out.println("Age : " + employee.getAge());
		System.out.println("Salary : " + employee.getSalary());
		System.out.println("designation : " + employee.getDesignation());
		System.out.println("contactNumber : " + employee.getContactNumber());
		System.out.println("emailId : " + employee.getEmailId());
		System.out.println("########################################################");

	}

The output of the above program is

We can get the JSON payload from a file present in a project under src/test/resources as shown in the below image.

public class EmployeeDeserializationGsonTest {

	@Test
	public void fromFile() throws FileNotFoundException {

		Gson gson = new Gson();
		// De-serializing from a json file
		String userDir = System.getProperty("user.dir");
		File inputJsonFile = new File(userDir + "\\src\\test\\resources\\EmployeePayloadUsingGson.json");
		FileReader fileReader = new FileReader(inputJsonFile);
		Employee employee1 = gson.fromJson(fileReader, Employee.class);

		// Now use getter method to retrieve values
		System.out.println("Details of Employee is as below:-");
		System.out.println("First Name : " + employee1.getFirstName());
		System.out.println("Last Name : " + employee1.getLastName());
		System.out.println("Age : " + employee1.getAge());
		System.out.println("Salary : " + employee1.getSalary());
		System.out.println("designation : " + employee1.getDesignation());
		System.out.println("contactNumber : " + employee1.getContactNumber());
		System.out.println("emailId : " + employee1.getEmailId());
		System.out.println("########################################################");
	}
}

The output of the above program is

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Deserialization – How to convert JSON to Map using Jackson API

HOME

This tutorial shows how to convert JSON to JAVA map using Jackson’s data binding. In the previous tutorials, I have explained converting Java Objects/Arrays to JSON String using Jackson API. You can refer below tutorials.

Serialization – How to create JSON Payload from Java Object – Jackson API

Deserialization – How to convert JSON to Java Object using Jackson API

How to create JSON Array Payload using POJO – Jackson API

How to create Nested JSON Object using POJO – Jackson API

To start with, we need to add Jackson Maven Dependency to the POM. Always add the latest version of Jackson dependency to your project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency

Deserialization converts a stream of bytes into a Java object that we can use in code.

We use Jackson’s ObjectMapper, as we did for serialization, using readValue() to process the input. Also, note our use of Jackson’s TypeReference, which we’ll use in all of our deserialization examples to describe the type of our destination Map.

   @Test
	public void DeserializationMapTest() throws JsonProcessingException {

		String employeeString = 
                     "{\r\n" 
                    + "  \"firstName\" : \"Deserialization\",\r\n"
				    + "  \"lastName\" : \"Test\",\r\n" 
                    + "  \"age\" : 25,\r\n" 
                    + "  \"salary\" : 50000.0,\r\n"
				    + "  \"designation\" : \"Manager\",\r\n" 
                    + "  \"contactNumber\" : \"+918882211111\",\r\n"
				    + "  \"emailId\" : \"abc@test.com\",\r\n" 
                    + "  \"gender\" : \"female\",\r\n"
				    + "  \"maritalStatus\" : \"single\"\r\n" 
                    + " }";

		Map<String, String> resultMap = new HashMap<String, String>();
		ObjectMapper mapper = new ObjectMapper();

		// Converting a JSON to Java Map
		try {
			resultMap = mapper.readValue(employeeString, new TypeReference<HashMap<String, String>>() {
			});
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		System.out.println("Output Map :" + resultMap);
	}

Output

We can get the JSON from a file and convert it to a Hash Map too. Below is an example of the same.

   @Test
	public void PayloadFromFile() {

		String userDir = System.getProperty("user.dir");
		ObjectMapper mapper = new ObjectMapper();

		// Converting Employee JSON string to Employee class object
		Map<String, Object> empMap;
		try {
			empMap = mapper.readValue(new File(userDir + "\\src\\test\\resources\\JSONFromMap.json"),
					new TypeReference<Map<String, Object>>() {
					});

			System.out.println("Gender : " + empMap.get("gender"));
			System.out.println("DOB : " + empMap.get("DOB"));
			System.out.println("Name : " + empMap.get("name"));
			System.out.println("ContactNumber : " + empMap.get("contactNumber"));
			System.out.println("SkillSet : " + empMap.get("skillset"));
		} catch (StreamReadException e) {
			e.printStackTrace();
		} catch (DatabindException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

Output

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Deserialization – How to convert JSON to Java Object using Jackson API

HOME

The previous tutorial explains the Serializarion process that means converting Java Objects to JSON Payload. This is done using Jackson API. This tutorial explains the Deserialization, means converting JSON Payload to Java Objects.

Deserialization – It is the reverse of serializing. In this process, we will read the Serialized byte stream from the file and convert it back into the Class instance representation. Here, we are converting a JSON Object to an Employee class object.

We are using Jackson API for Serialization and Deserialization. So, add the Jackson dependency to the project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

Below is the sample code of the Employee table, which contains the data members needed for Employee JSON and their corresponding getter and setter methods.

public class Employee {
 
    // private variables or data members of POJO class
    private String firstName;
    private String lastName;
    private int age;
    private double salary;
    private String designation;
    private String contactNumber;
    private String emailId;
 
    // Getter and setter methods
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public double getSalary() {
        return salary;
    }
 
    public void setSalary(double salary) {
        this.salary = salary;
    }
 
    public String getDesignation() {
        return designation;
    }
 
    public void setDesignation(String designation) {
        this.designation = designation;
    }
     
    public String getContactNumber() {
        return contactNumber;
    }
 
    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }
 
    public String getEmailId() {
        return emailId;
    }
 
    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }
 
}

Now, let us create a Test Class to show Deserialization.

    @Test
    public void deserializationTest() {
 
        Employee employee = new Employee();
        employee.setFirstName("Tim");
        employee.setLastName("Tran");
        employee.setAge(49);
        employee.setSalary(89000);
        employee.setDesignation("Manager");
        employee.setContactNumber("+3538944412341");
        employee.setEmailId("ttran@test.com");
 
        // Converting a Java class object to a JSON payload as string
        ObjectMapper mapper = new ObjectMapper();
        String employeeJson = null;
        try {
            employeeJson = mapper.writeValueAsString(employee);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
 
        // Converting Employee json string to Employee class object

        try {
            Employee employee2 = mapper.readValue(employeeJson, Employee.class);
            System.out.println("First Name of employee : " + employee2.getFirstName());
            System.out.println("Last Name of employee : " + employee2.getLastName());
            System.out.println("Age of employee : " + employee2.getAge());
            System.out.println("Salary of employee : " + employee2.getSalary());
            System.out.println("Designation of employee : " + employee2.getDesignation());
            System.out.println("Contact Number of employee : " + employee2.getContactNumber());
            System.out.println("EmailId of employee : " + employee2.getEmailId());
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }

We can read JSON String and convert it back to Java Object as shown below. We will use readValue() to deserialize JSON content from the given file into a given Java type.

This is my JSON saved in a file placed at Desktop.

Below is the Test

@Test
public void readJson() {
 
    ObjectMapper mapper = new ObjectMapper();
 
    // Converting Employee JSON string to Employee class object
    try {
          Employee employee2 = mapper.readValue(new File(
                "C:\\Users\\Vibha\\Desktop\\Employee.json"),
                Employee.class);
          System.out.println("First Name of employee : " + employee2.getFirstName());
          System.out.println("Last Name of employee : " + employee2.getLastName());
          System.out.println("Age of employee : " + employee2.getAge());
          System.out.println("Salary of employee : " + employee2.getSalary());
          System.out.println("Designation of employee : " + employee2.getDesignation());
          System.out.println("Contact Number of employee : " + employee2.getContactNumber());
          System.out.println("EmailId of employee : " + employee2.getEmailId());
    } catch (StreamReadException e) {
        e.printStackTrace();
    } catch (DatabindException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I hope this has helped to clear your doubts regarding how to create Java Objects from JSON using Jackson API.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Rest Assured – @JsonIgnoreProperties in Jackson

HOME

This tutorial will show how to ignore certain fields when serializing an object to JSON or deserializing the JSON to object using Jackson 2.x.

This is very useful when the Jackson defaults aren’t enough and we need to control exactly what gets serialized to JSON – and there are several ways to ignore properties. One of the most common way is the use of @JsonIgnore Annotation, but it has some limitations. One of the major limitation is that if it is applied to getter method only, it will ignore setter method too. So, we cannot control if we want a property to be ignored for either Serialization or Deserialization.

Moreover, when there is a requirement to ignore multiple properties, it is tedious to mention @JsonIgnore to all the properties which need to be ignored. Imagine there are 100 properties and we need to ignore 30 properties, it is tedious to mention @JsonIgnore to each properties.

To start of, add Jackson databind dependency to the project. Always add the latest dependency to your project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

We can ignore specific fields at the class level, using the @JsonIgnoreProperties annotation and specifying the fields by name.

Syntax

@JsonIgnoreProperties({"emailId","gender","maritalStatus"})

Sample JSON Payload

{
  "firstName" : "Vibha",
  "lastName" : "Singh",
  "age" : 30,
  "salary" : 75000.0,
  "designation" : "Manager",
  "contactNumber" : "+919999988822",
  "emailId" : "abc@test.com",
  "gender" : "female",
  "maritalStatus" : "married"
 }

We need to create POJO for above JSON. So, let us create a class called Employee. Then create the private data members corresponding to the the nodes of the JSON and the getter and setter methods of these data members.

POJO Class

@JsonIgnoreProperties({"emailId","gender","maritalStatus"})
public class Employee {

	// private variables or data members of pojo class
	private String firstName;
	private String lastName;
	private int age;
	private double salary;
	private String designation;
	private String contactNumber;
	private String emailId;
	private String gender;
	private String maritalStatus;

	// Getter and setter methods
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public String getContactNumber() {
		return contactNumber;
	}

	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getMaritalStatus() {
		return maritalStatus;
	}

	public void setMaritalStatus(String maritalStatus) {
		this.maritalStatus = maritalStatus;
	}

}

Here, we have added emailId, gender and maritalStatus to @JsonIgnoreProperties as shown above.

Let us create a test where we pass values to all the nodes present in the JSON and see what happens to properties – emailId, gender and maritalStatus which are tagged as @JsonIgnoreProperties.

SerializationTest

    @Test
	public void serializationTest()  {

		// Create an object of POJO class
		Employee employee = new Employee();
		employee.setFirstName("Vibha");
		employee.setLastName("Singh");
		employee.setAge(30);
		employee.setSalary(75000);
		employee.setDesignation("Manager");
		employee.setContactNumber("+919999988822");
		employee.setEmailId("abc@test.com");
		employee.setMaritalStatus("married");
		employee.setGender("female");

		// Converting a Java class object to a JSON payload as string
		ObjectMapper mapper = new ObjectMapper();
		try {
			String employeeJson = mapper.writeValueAsString(employee);
			System.out.println(employeeJson);
			String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
			System.out.println(employeePrettyJson);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
}

Output

You can see that emailId, gender and maritalStatus are not present in JSON Payload.

Let us see the impact of @JsonIgnoreProperties to the setter or deserialized properties.

Deserialization Test

    @Test
	public void deserializationTest()  {

		String employeeString = "{\r\n"
				+ "  \"firstName\" : \"Deserialization\",\r\n"
				+ "  \"lastName\" : \"Test\",\r\n"
				+ "  \"age\" : 30,\r\n"
				+ "  \"salary\" : 75000.0,\r\n"
				+ "  \"designation\" : \"Manager\",\r\n"
				+ "  \"contactNumber\" : \"+919999988822\",\r\n"
				+ "  \"emailId\" : \"abc@test.com\",\r\n"
				+ "  \"gender\" : \"female\",\r\n"
				+ "  \"maritalStatus\" : \"married\"\r\n"
				+ " }";
		
	
		// Converting a JSON Payload to a JAVA Object
		ObjectMapper mapper = new ObjectMapper();
        Employee employee2 = null;

		try {
			employee2 = mapper.readValue(employeeString, Employee.class);
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		System.out.println("First Name of employee : " + employee2.getFirstName());
		System.out.println("Last Name of employee : " + employee2.getLastName());
		System.out.println("Age of employee : " + employee2.getAge());
		System.out.println("Salary of employee : " + employee2.getSalary());
		System.out.println("Designation of employee : " + employee2.getDesignation());
		System.out.println("Contact Number of employee : " + employee2.getContactNumber());
		System.out.println("EmailId of employee : " + employee2.getEmailId());
		System.out.println("Marital Status of employee : " + employee2.getMaritalStatus());
		System.out.println("Gender of employee : " + employee2.getGender());

	}

Output

You can see that emailId, gender and maritalStatus – the values present in JSON for all of them are ignored and default values are retrieved.

POJO with allowGetters

allowGetters are enabled to allow “getters” to be used. This is commonly set to support defining “read-only” properties; ones for which there is a getter, but no matching setter: in this case, properties should be ignored for deserialization but NOT serialization. Another way to think about this setting is that setting it to `true` will “disable” ignoring of getters.

Default value is `false`, which means that getters with matching names will be ignored.

In the below example, I have defined emailId, gender and maritalStatus as allowGetters as True.

public class EmployeeTest {
	
	@Test
	public void serializationTest()  {

		Employee employee = new Employee();
		employee.setFirstName("Vibha");
		employee.setLastName("Singh");
		employee.setAge(30);
		employee.setSalary(75000);
		employee.setDesignation("Manager");
		employee.setContactNumber("+919999988822");
		employee.setEmailId("abc@test.com");
		employee.setMaritalStatus("married");
		employee.setGender("female");

		// Converting a Java class object to a JSON payload as string
		ObjectMapper mapper = new ObjectMapper();
      
        try {		
			String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
			System.out.println(employeePrettyJson);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		
	}

	@Test
	public void deserializationTest() {

		String employeeString = "{\r\n"
				+ "  \"firstName\" : \"Deserialization\",\r\n"
				+ "  \"lastName\" : \"Test\",\r\n"
				+ "  \"age\" : 30,\r\n"
				+ "  \"salary\" : 75000.0,\r\n"
				+ "  \"designation\" : \"Manager\",\r\n"
				+ "  \"contactNumber\" : \"+919999988822\",\r\n"
				+ "  \"emailId\" : \"abc@test.com\",\r\n"
				+ "  \"gender\" : \"female\",\r\n"
				+ "  \"maritalStatus\" : \"married\"\r\n"
				+ " }";
		
	
		// Converting a JSON Payload to a JAVA Object
		ObjectMapper mapper = new ObjectMapper();

		 Employee employee2 = null;

		try {
			employee2 = mapper.readValue(employeeString, Employee.class);
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		System.out.println("First Name of employee : " + employee2.getFirstName());
		System.out.println("Last Name of employee : " + employee2.getLastName());
		System.out.println("Age of employee : " + employee2.getAge());
		System.out.println("Salary of employee : " + employee2.getSalary());
		System.out.println("Designation of employee : " + employee2.getDesignation());
		System.out.println("Contact Number of employee : " + employee2.getContactNumber());
		System.out.println("EmailId of employee : " + employee2.getEmailId());
		System.out.println("Marital Status of employee : " + employee2.getMaritalStatus());
		System.out.println("Gender of employee : " + employee2.getGender());

	}

}

Output

In the below image, it shows that values of emailId, gender and maritalStatus are ignored and default value is passed.

POJO with allowSetters

allowSetters – Property that can be enabled to allow “setters” to be used. This could be used to specify “write-only” properties; ones that should not be serialized out, but that may be provided in for deserialization. Another way to think about this setting is that setting it to `true` will “disable” ignoring of setters.

Default value is `false`, which means that setters with matching names will be ignored.

public class EmployeeTest {
	
	@Test
	public void serializationTest() {

		Employee employee = new Employee();
		employee.setFirstName("Vibha");
		employee.setLastName("Singh");
		employee.setAge(30);
		employee.setSalary(75000);
		employee.setDesignation("Manager");
		employee.setContactNumber("+919999988822");
		employee.setEmailId("abc@test.com");
		employee.setMaritalStatus("married");
		employee.setGender("female");

		// Converting a Java class object to a JSON payload as string
		ObjectMapper mapper = new ObjectMapper();
		try {		
			String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
			System.out.println(employeePrettyJson);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		System.out.println("########################################");
	}

	@Test
	public void deserializationTest()  {

		String employeeString = "{\r\n"
				+ "  \"firstName\" : \"Deserialization\",\r\n"
				+ "  \"lastName\" : \"Test\",\r\n"
				+ "  \"age\" : 30,\r\n"
				+ "  \"salary\" : 75000.0,\r\n"
				+ "  \"designation\" : \"Manager\",\r\n"
				+ "  \"contactNumber\" : \"+919999988822\",\r\n"
				+ "  \"emailId\" : \"abc@test.com\",\r\n"
				+ "  \"gender\" : \"female\",\r\n"
				+ "  \"maritalStatus\" : \"married\"\r\n"
				+ " }";
		
	
		// Converting a JSON Payload to a JAVA Object
		ObjectMapper mapper = new ObjectMapper();

		 Employee employee2 = null;

		try {
			employee2 = mapper.readValue(employeeString, Employee.class);
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		System.out.println("First Name of employee : " + employee2.getFirstName());
		System.out.println("Last Name of employee : " + employee2.getLastName());
		System.out.println("Age of employee : " + employee2.getAge());
		System.out.println("Salary of employee : " + employee2.getSalary());
		System.out.println("Designation of employee : " + employee2.getDesignation());
		System.out.println("Contact Number of employee : " + employee2.getContactNumber());
		System.out.println("EmailId of employee : " + employee2.getEmailId());
		System.out.println("Marital Status of employee : " + employee2.getMaritalStatus());
		System.out.println("Gender of employee : " + employee2.getGender());
		
		System.out.println("########################################");

	}

}

Output

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Rest Assured – @JsonIgnore Annotation in Jackson API

HOME

This tutorial will show how to ignore certain fields when serializing an object to JSON using Jackson 2.x.

This is very useful when the Jackson defaults aren’t enough, and we need to control exactly what gets serialized to JSON – and there are several ways to ignore properties. One of the most common ways is the use of @JsonIgnore Annotation.

To start off, add Jackson’s databind dependency to the project. Always add the latest dependency to your project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

@JsonIgnore is used at field level to mark a property or list of properties to be ignored.

The Jackson’s @JsonIgnore annotation can be placed on fields, getters/setters and constructor parameters mark a property to be ignored during the serialization to JSON (or deserialization from JSON).  If @JsonIgnore is the only annotation associated with a property, it will also cause the whole property to be ignored: that is, if setter has this annotation and getter has no annotations, the getter is also effectively ignored.

Let us have an Employee JSON as shown below.

{
  "firstName" : "Vibha",
  "lastName" : "Singh",
  "age" : 30,
  "salary" : 75000.0,
  "designation" : "Manager",
  "contactNumber" : "+919999988822",
  "emailId" : "abc@test.com",
  "gender" : "female",
  "maritalStatus" : "married"
}

To learn about Serialization and Deserialization of a JSON Object using Jackson API, refer to this

To create a POJO of the above JSON, we need to create a class with the name Employee. Create private data members corresponding to these JSON nodes, and then create the corresponding getter and setter methods.

Here, I have assigned emailId and gender as @JsonIgnore.

public class Employee {

	// private variables or data members of pojo class
	private String firstName;
	private String lastName;
	private int age;
	private double salary;
	private String designation;
	private String contactNumber;

	@JsonIgnore
	private String emailId;

	@JsonIgnore
	private String gender;

	private String maritalStatus;

	// Getter and setter methods
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public String getContactNumber() {
		return contactNumber;
	}

	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getMaritalStatus() {
		return maritalStatus;
	}

	public void setMaritalStatus(String maritalStatus) {
		this.maritalStatus = maritalStatus;
	}

}

Now, let us create a SerializationTest with the above-mentioned POJO.

	@Test
	public void serializationTest() {

		Employee employee = new Employee();
		employee.setFirstName("Vibha");
		employee.setLastName("Singh");
		employee.setAge(30);
		employee.setSalary(75000);
		employee.setDesignation("Manager");
		employee.setContactNumber("+919999988822");
		employee.setEmailId("abc@test.com");
		employee.setMaritalStatus("married");
		employee.setGender("female");

		// Converting a Java class object to a JSON payload as string
		ObjectMapper mapper = new ObjectMapper();

		try {
			String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
			System.out.println(employeePrettyJson);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		System.out.println("########################################");

	}

Output

As you can see here that emailId and gender nodes are not present in this JSON payload.

Now, let us see an example of deserialization where nodes that are assigned as @JsonIgnore return null values.

@Test
	public void deserializationTest() throws JsonMappingException, JsonProcessingException  {

		String employeeString = "{\r\n"
				+ "  \"firstName\" : \"Deserialization\",\r\n"
				+ "  \"lastName\" : \"Test\",\r\n"
				+ "  \"age\" : 30,\r\n"
				+ "  \"salary\" : 75000.0,\r\n"
				+ "  \"designation\" : \"Manager\",\r\n"
				+ "  \"contactNumber\" : \"+919999988822\",\r\n"
				+ "  \"emailId\" : \"abc@test.com\",\r\n"
				+ "  \"gender\" : \"female\",\r\n"
				+ "  \"maritalStatus\" : \"married\"\r\n"
				+ " }";
		
	
		// Converting a Java class object to a JSON payload as string
		ObjectMapper mapper = new ObjectMapper();

		Employee employee2 = mapper.readValue(employeeString, Employee.class);
		System.out.println("First Name of employee : " + employee2.getFirstName());
		System.out.println("Last Name of employee : " + employee2.getLastName());
		System.out.println("Age of employee : " + employee2.getAge());
		System.out.println("Salary of employee : " + employee2.getSalary());
		System.out.println("Designation of employee : " + employee2.getDesignation());
		System.out.println("Contact Number of employee : " + employee2.getContactNumber());
		System.out.println("EmailId of employee : " + employee2.getEmailId());
		System.out.println("Marital Status of employee : " + employee2.getMaritalStatus());
		System.out.println("Gender of employee : " + employee2.getGender());

	}

Output

We have values for fields emailId and gender in JSON, but it has not been deserialized as you can see it has default values, not from JSON.

I hope this has helped you to understand @JsonIgnore. Cheers!! Have happy learning!!

Rest Assured – How to test JSON Request using Jackson API

HOME

This tutorial focuses on the testing of a REST API (with JSON payload). We will use Jackson API to serialize the request.

It is suggested to go through these tutorials to understand about creating a JSON Object Payload using POJO (Plain Old Java Object).

How to create JSON Object Payload using POJO – Jackson API

How to create JSON Array Payload using POJO – Jackson API

How to create Nested JSON Object using POJO – Jackson API

To start with, we need to add Jackson Maven’s Dependency to the POM. Always add the latest version of Jackson dependency to your project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

The complete POM.xml will look like this, as shown below:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>RestAssured_JUnit4_Demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <rest-assured.version>5.3.0</rest-assured.version>
        <junit.version>4.13.2</junit.version>
        <jackson.version>2.14.3</jackson.version>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- Rest-Assured Dependency -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest-assured.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- JUnit4 Dependency -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- Jackson Dependency -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- Hamcrest Dependency -->
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

This dependency will also transitively add the following libraries to the classpath:

  1. jackson-annotations
  2. jackson-core

In the below example, let us assume that we need to create a new Employee (POST Request). To start with, we need to create a POJO class of the JSON payload (EmployeeDetails). This POJO class should contain the data members corresponding to the JSON nodes and their corresponding getter and setter methods.

public class EmployeeDetails {

	// private variables or data members of pojo class
	private String name;
	private double salary;
	private int age;

    // Getter and Setters
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

Now that we have our POJO class, we can start writing some REST Assured Serialization tests!

Let’s start with REST Assured Serialization with JSON. I want to send a POST request to my EmployeeDetails API that will add a new Employee to the database. I will send a POJO of the employee in the request body. This is what the code looks like in the test class:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.http.ContentType;
import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class EmployeeTests {

    @Test
    public void createEmployee() {

        // Create an object of POJO class
        EmployeeDetails emp = new EmployeeDetails();
        emp.setName("Vibha");
        emp.setSalary(75000);
        emp.setAge(30);

        // Converting a Java class object to a JSON payload as string
        ObjectMapper mapper = new ObjectMapper();
        String employeePrettyJson = null;
        try {
            employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        System.out.println("Request");
        System.out.println(employeePrettyJson);
        System.out.println("=========================================");
        System.out.println("Response");

        // GIVEN
        given().baseUri("https://dummy.restapiexample.com/api").contentType(ContentType.JSON).body(emp)

                // WHEN
                .when().post("/v1/create")

                // THEN
                .then().assertThat().statusCode(200).body("data.name", equalTo("Vibha"))
                .body("message", equalTo("Successfully! Record has been added.")).log().body();

    }

}

The output of the above program is

If you want to see the structure of the Request, then add the below in the test code.

ObjectMapper mapper = new ObjectMapper();
String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
System.out.println(employeePrettyJson);

REST Assured Serialization with Jackson handled all the serialization work for us. Great! See, this has become so simple with the help of Jackson API.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to create Nested JSON Object using POJO – Jackson API

HOME

In the previous tutorial, I explained the creation of JSON Array using POJO. In this tutorial, I will explain the creation of a nested JSON Object (JSON with multiple nodes) using POJO.

It is recommended to go through these tutorials to understand POJO, JSON Object, and JSON Array.

How to create JSON Object Payload using POJO – Jackson API

How to create JSON Array Payload using POJO – Jackson API

We are using Jackson API for Serialization and Deserialization. So, add the Jackson dependency to the project. We need to add the below-mentioned dependencies to run this example.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>RestAssured_JUnit4_Demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <junit.version>4.13.2</junit.version>
        <jackson.version>2.14.2</jackson.version>
        <hamcrest.version>1.3</hamcrest.version>
    </properties>

    <dependencies>

        <!-- JUnit4 Dependency -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- Jackson Dependency -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- Hamcrest Dependency -->
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>${hamcrest.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

We will use a nested JSON Object (a combination of JSON Arrays and objects).

{
  "companyName": "QAAutomation",
  "companyEmailId": "qaautomation@org.com",
  "companyNumber": "+353891234121", 
  "companyAddress": "12, HeneryStreet, Dublin, D12PW20", 
  "supportedSalaryBanks": [
    "AIB",
    "BOI",
    "PSB"
  ],
  "employee": [
    { 
	  "firstName" : "Vibha",
      "lastName" : "Singh",
      "age" : 30,
      "salary" : 75000.0,
      "designation" : "Manager",
      "contactNumber" : "+919999988822",
      "emailId" : "abc@test.com"
    },
    {
      "firstName" : "Neha",
      "lastName" : "Verma",
      "age" : 25,
      "salary" : 60000.0,
      "designation" : "Lead",
      "contactNumber" : "+914442266221",
      "emailId" : "xyz@test.com"
    },
    {
      "firstName" : "Rajesh",
      "lastName" : "Gupta",
      "age" : 20,
      "salary" : 40000.0,
      "designation" : "Intern",
      "contactNumber" : "+919933384422",
      "emailId" : "pqr@test.com"
    }
  ],
  "contractors": [
    {
      "firstName": "John",
      "lastName": "Mathew",
      "contractFrom": "Jan-2018",
      "contractTo": "Aug-2022",
	  "contactNumber" : "+919631384422"
    },
    {
      "firstName": "Seema",
      "lastName": "Prasad",
      "contractFrom": "Jun-2019",
      "contractTo": "Jun-2023"
	  "contactNumber" : "+919688881422"
    }
  ],
  "companyPFDeails": {
    "pfName": "XYZ",
    "pfYear": 2020,
    "noOfEmployees": 100
  }
}

It is very overwhelming to handle this type of nested JSON Object at a glance. So, we will split this into small parts or objects. So basically, we can split the above JSON into 4 parts – Employee, Contractors, CompanyPFDetails, and NestedPOJODemo.

companyName, companyEmailId, companyNumber, and companyAddress are 1:1 mapping in the payload. supportedSalaryBanks is an array of String values.

	private String companyName;
	private String companyEmailId;
	private String companyNumber;
	private String companyAddress;
	private List<String> supportedSalaryBanks;

Employee has value as an array of employees. There is no ready-made data type to represent elements of this array as a whole. So here we need to create a POJO class that can contain all details of an employee.

To represent an array of Employees and Contractors

	List<Employee> employee;
	List<Contractors> contractors;

Create a POJO class for CompanyPFDetails and add it to the main payload.

Now, let us see various POJO classes.

Employee POJO Class

public class Employee {

	// private variables or data members of pojo class
	private String firstName;
	private String lastName;
	private int age;
	private double salary;
	private String designation;
	private String contactNumber;
	private String emailId;

	// Getter and setter methods
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public String getContactNumber() {
		return contactNumber;
	}

	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

}

Contractors POJO Class

public class Contractors {

	// private variables or data members of pojo class
	private String firstName;
	private String lastName;
	private String contractFrom;
	private String contractTo;
	private String contactNumber;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getContractFrom() {
		return contractFrom;
	}

	public void setContractFrom(String contractFrom) {
		this.contractFrom = contractFrom;
	}

	public String getContractTo() {
		return contractTo;
	}

	public void setContractTo(String contractTo) {
		this.contractTo = contractTo;
	}

	public String getContactNumber() {
		return contactNumber;
	}

	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
	}

}

CompanyPFDetails POJO Class

public class CompanyPFDetails {

	private String pfName;
	private int pfYear;
	private int noOfEmployees;

	public String getPfName() {
		return pfName;
	}

	public void setPfName(String pfName) {
		this.pfName = pfName;
	}

	public int getPfYear() {
		return pfYear;
	}

	public void setPfYear(int pfYear) {
		this.pfYear = pfYear;
	}

	public int getNoOfEmployees() {
		return noOfEmployees;
	}

	public void setNoOfEmployees(int noOfEmployees) {
		this.noOfEmployees = noOfEmployees;
	}

}

NestedPOJODemo class

public class NestedPOJODemo {

	// private variables or data members of pojo class
	private String companyName;
	private String companyEmailId;
	private String companyNumber;
	private String companyAddress;
	private List<String> supportedSalaryBanks;
	List<Employee> employee;
	List<Contractors> contractors;
	CompanyPFDetails companyPFDetails;

	public String getCompanyName() {
		return companyName;
	}

	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}

	public String getCompanyEmailId() {
		return companyEmailId;
	}

	public void setCompanyEmailId(String companyEmailId) {
		this.companyEmailId = companyEmailId;
	}

	public String getCompanyNumber() {
		return companyNumber;
	}

	public void setCompanyNumber(String companyNumber) {
		this.companyNumber = companyNumber;
	}

	public String getCompanyAddress() {
		return companyAddress;
	}

	public void setCompanyAddress(String companyAddress) {
		this.companyAddress = companyAddress;
	}

	public List<String> getSupportedSalaryBanks() {
		return supportedSalaryBanks;
	}

	public void setSupportedSalaryBanks(List<String> supportedSalaryBanks) {
		this.supportedSalaryBanks = supportedSalaryBanks;
	}

	public List<Employee> getEmployee() {
		return employee;
	}

	public void setEmployee(List<Employee> employee) {
		this.employee = employee;
	}

	public List<Contractors> getContractors() {
		return contractors;
	}

	public void setContractors(List<Contractors> contractors) {
		this.contractors = contractors;
	}

	public CompanyPFDetails getCompanyPFDetails() {
		return companyPFDetails;
	}

	public void setCompanyPFDetails(CompanyPFDetails companyPFDetails) {
		this.companyPFDetails = companyPFDetails;
	}

}

Let’s create a JSON Payload using the above POJO classes.

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class NestedPOJOTest {

    @Test
    public void createNestedPOJO() throws IOException {

        NestedPOJODemo demo = new NestedPOJODemo();
        demo.setCompanyName("QAAutomation");
        demo.setCompanyEmailId("qaautomation@org.com");
        demo.setCompanyNumber("+353891234121");
        demo.setCompanyAddress("12, HeneryStreet, Dublin, D12PW20");

        List<String> supportedSalaryBanks = new ArrayList<String>();
        supportedSalaryBanks.add("AIB");
        supportedSalaryBanks.add("BOI");
        supportedSalaryBanks.add("PSB");
        demo.setSupportedSalaryBanks(supportedSalaryBanks);

        // First Employee
        Employee emp1 = new Employee();
        emp1.setFirstName("Vibha");
        emp1.setLastName("Singh");
        emp1.setAge(30);
        emp1.setSalary(75000);
        emp1.setDesignation("Manager");
        emp1.setContactNumber("+919999988822");
        emp1.setEmailId("abc@test.com");

        // Second Employee
        Employee emp2 = new Employee();
        emp2.setFirstName("Neha");
        emp2.setLastName("Verms");
        emp2.setAge(35);
        emp2.setSalary(60000);
        emp2.setDesignation("Lead");
        emp2.setContactNumber("+914442266221");
        emp2.setEmailId("xyz@test.com");

        // Third Employee
        Employee emp3 = new Employee();
        emp3.setFirstName("Rajesh");
        emp3.setLastName("Gupta");
        emp3.setAge(20);
        emp3.setSalary(40000);
        emp3.setDesignation("Intern");
        emp3.setContactNumber("+919933384422");
        emp3.setEmailId("pqr@test.com");

        // Creating a List of Employees
        List<Employee> employeeList = new ArrayList<Employee>();
        employeeList.add(emp1);
        employeeList.add(emp2);
        employeeList.add(emp3);
        demo.setEmployee(employeeList);

        // First Contractor
        Contractors contractor1 = new Contractors();
        contractor1.setFirstName("John");
        contractor1.setLastName("Mathew");
        contractor1.setContractFrom("Jan-2018");
        contractor1.setContractTo("Aug-2022");
        contractor1.setContactNumber("+919631384422");

        // Second Contractor
        Contractors contractor2 = new Contractors();
        contractor2.setFirstName("Seema");
        contractor2.setLastName("Mathew");
        contractor2.setContractFrom("Jun-2019");
        contractor2.setContractTo("Jun-2023");
        contractor2.setContactNumber("+919688881422");

        // Creating a List of Contractors
        List<Contractors> contractorList = new ArrayList<Contractors>();
        contractorList.add(contractor1);
        contractorList.add(contractor2);
        demo.setContractors(contractorList);

        CompanyPFDetails pf = new CompanyPFDetails();
        pf.setPfName("XYZ");
        pf.setPfYear(2020);
        pf.setNoOfEmployees(100);
        demo.setCompanyPFDetails(pf);

        ObjectMapper mapper = new ObjectMapper();
        String nestedJsonPayload = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(demo);
        System.out.println(nestedJsonPayload);

    }

}

Here, I have used ObjectMapper for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.

We can save this JSON payload in a file in the project or any location of your choice. Here, I’m saving this Nested JSON Payload in a file within src/test/resources.

String userDir = System.getProperty("user.dir");
mapper.writerWithDefaultPrettyPrinter().writeValue(new File(userDir + "\\src\\test\\resources\\NestedEmployeePayload.json"), demo);
	}

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to create JSON Array Payload using POJO – Jackson API

HOME

In the previous tutorial, I have explained the creation of JSON Object using POJO. In this tutorial, will create a JSON Array Payload using POJO.

To know about POJO, please refer to this tutorial.

You can refer these tutorials to understand various ways of using Jackson API

Serialization – How to create JSON Payload from Java Object – Jackson API

How to create JSON Array Payload using POJO – Jackson API

How to create Nested JSON Object using POJO – Jackson API

Serialization – How to convert Map to JSON string using Jackson API

JSON Array is a collection of JSON Objects. In the below example, will create a list of employees.

The sample JSON Array structure looks like the image as shown below:-

{
  "firstName" : "Vibha",
  "lastName" : "Singh",
  "age" : 30,
  "salary" : 75000.0,
  "designation" : "Manager",
  "contactNumber" : "+919999988822",
  "emailId" : "abc@test.com"
  
  "firstName" : "Neha",
  "lastName" : "Verma",
  "age" : 25,
  "salary" : 60000.0,
  "designation" : "Lead",
  "contactNumber" : "+914442266221",
  "emailId" : "xyz@test.com"
  
  "firstName" : "Rajesh",
  "lastName" : "Gupta",
  "age" : 20,
  "salary" : 40000.0,
  "designation" : "Intern",
  "contactNumber" : "+919933384422",
  "emailId" : "pqr@test.com"
}

We need to create an Employee class that contains private data members and corresponding getter and setter methods of these data members.

Below is an Employee Class with private data members, as well as the corresponding getter and setter methods of these data members. Every IDE provides a shortcut to create these getter and setter methods.

public class Employee {

	// private variables or data members of POJO class
	private String firstName;
	private String lastName;
	private int age;
	private double salary;
	private String designation;
	private String contactNumber;
	private String emailId;

	// Getter and setter methods
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public String getContactNumber() {
		return contactNumber;
	}

	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

}

Serialization – Serialization is a process where you convert an Instance of a Class (Object of a class) into a Byte Stream. Here, we are converting Employee class object to JSON Array representation or Object.

Deserialization – It is the reverse of serializing. In this process, we will read the Serialized byte stream from the file and convert it back into the Class instance representation. Here, we are converting a JSON Array to an Employee class object.

We are using Jackson API for Serialization and Deserialization. So, add the Jackson dependency to the project.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

Below is the class where we will assign values to the data members by using getter methods (Serialization).

public class EmployeeArrayTest {

	@Test
	public void createEmployeeArray() {

		Employee emp1 = new Employee();
		emp1.setFirstName("Vibha");
		emp1.setLastName("Singh");
		emp1.setAge(30);
		emp1.setSalary(75000);
		emp1.setDesignation("Manager");
		emp1.setContactNumber("+919999988822");
		emp1.setEmailId("abc@test.com");

		Employee emp2 = new Employee();
		emp2.setFirstName("Neha");
		emp2.setLastName("Verms");
		emp2.setAge(35);
		emp2.setSalary(60000);
		emp2.setDesignation("Lead");
		emp2.setContactNumber("+914442266221");
		emp2.setEmailId("xyz@test.com");

		Employee emp3 = new Employee();
		emp3.setFirstName("Rajesh");
		emp3.setLastName("Gupta");
		emp3.setAge(20);
		emp3.setSalary(40000);
		emp3.setDesignation("Intern");
		emp3.setContactNumber("+919933384422");
		emp3.setEmailId("pqr@test.com");

		// Creating a List of Employees
		List<Employee> employeeList = new ArrayList<Employee>();
		employeeList.add(emp1);
		employeeList.add(emp2);
		employeeList.add(emp3);

		// Converting a Java class object to a JSON Array Payload as string
		ObjectMapper mapper = new ObjectMapper();
		try {
			String allEmployeeJson = mapper.writeValueAsString(employeeList);
			String employeeListPrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employeeList);
			System.out.println(allEmployeeJson);
			System.out.println(employeeListPrettyJson);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
	}

ObjectMapper is imported from:-

import com.fasterxml.jackson.databind.ObjectMapper;

In the below example, we are deserializing the JSON Array Payload to Java objects.

    @Test
	public void getEmployeeArray() {

		Employee emp1 = new Employee();
		emp1.setFirstName("Vibha");
		emp1.setLastName("Singh");
		emp1.setAge(30);
		emp1.setSalary(75000);
		emp1.setDesignation("Manager");
		emp1.setContactNumber("+919999988822");
		emp1.setEmailId("abc@test.com");

		Employee emp2 = new Employee();
		emp2.setFirstName("Neha");
		emp2.setLastName("Verms");
		emp2.setAge(35);
		emp2.setSalary(60000);
		emp2.setDesignation("Lead");
		emp2.setContactNumber("+914442266221");
		emp2.setEmailId("xyz@test.com");

		Employee emp3 = new Employee();
		emp3.setFirstName("Rajesh");
		emp3.setLastName("Gupta");
		emp3.setAge(20);
		emp3.setSalary(40000);
		emp3.setDesignation("Intern");
		emp3.setContactNumber("+919933384422");
		emp3.setEmailId("pqr@test.com");

		// Creating a List of Employees
		List<Employee> employeeList = new ArrayList<Employee>();
		employeeList.add(emp1);
		employeeList.add(emp2);
		employeeList.add(emp3);

		// Converting a Java class object to a JSON Array Payload as string

		ObjectMapper mapper = new ObjectMapper();
		String allEmployeeJson = null;

		try {
			allEmployeeJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employeeList);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		List<Employee> allEmployeeDetails = null;
		try {
			allEmployeeDetails = mapper.readValue(allEmployeeJson, new TypeReference<List<Employee>>() {
			});
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		for (Employee emp : allEmployeeDetails) {

			System.out.println("===================================");

			System.out.println("First Name of employee : " + emp.getFirstName());
			System.out.println("Last Name of employee : " + emp.getLastName());
			System.out.println("Age of employee : " + emp.getAge());
			System.out.println("Salary of employee : " + emp.getSalary());
			System.out.println("Designation of employee : " + emp.getDesignation());
			System.out.println("Contact Number of employee : " + emp.getContactNumber());
			System.out.println("EmailId of employee : " + emp.getEmailId());
		}
	}

If you want to read the data from a file placed on Desktop, below is the sample code for the same.

@Test
	public void readArrayJsonFromFile() throws IOException {

		ObjectMapper mapper = new ObjectMapper();

		// Converting Employee json string to Employee class object
		List<Employee> allEmployeeDetails = null;
		try {
			allEmployeeDetails = mapper.readValue(new File(
					"C:\\Users\\Vibha\\Desktop\\EmployeeList.json"),
					new TypeReference<List<Employee>>() {
					});
		} catch (StreamReadException e) {
			e.printStackTrace();
		} catch (DatabindException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}


		for (Employee emp : allEmployeeDetails) {

			System.out.println("######################################");

			System.out.println("First Name of employee : " + emp.getFirstName());
			System.out.println("Last Name of employee : " + emp.getLastName());
			System.out.println("Age of employee : " + emp.getAge());
			System.out.println("Salary of employee : " + emp.getSalary());
			System.out.println("Designation of employee : " + emp.getDesignation());
			System.out.println("Contact Number of employee : " + emp.getContactNumber());
			System.out.println("EmailId of employee : " + emp.getEmailId());
		}
	}

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!