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 Version 3 dependencies to your pom file.
Now, let us create the Java Objects (POJO) of above XML.
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "EmployeeDetail")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee {
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;
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 + "]";
}
}
Let’s create a simple program using the JAXBContextwhich provides an abstraction for managing the XML/Java binding information necessary to implement the JAXB binding framework operations and unmarshal.
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 Unmarshaller class governs the process of deserializing XML data into newly created Java content trees, optionally validating the XML data as it is unmarshalled. It provides overloading of unmarshal methods for many input kinds.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
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 Version 3 dependencies to your pom file.
Now, let us create the Java Objects (POJO) of the above XML.
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "EmployeeDetail")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee {
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;
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 + "]";
}
}
Let’s create a simple program using the JAXBContextwhich provides an abstraction for managing the XML/Java binding information necessary to implement the JAXB binding framework operations.
import java.io.StringWriter;
import org.junit.Test;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.PropertyException;
public class JAXBSerialization {
@Test
public void serializationTest1() {
try {
Employee employee = new Employee();
employee.setFirstName("Terry");
employee.setLastName("Mathew");
employee.setAge(30);
employee.setSalary(75000);
employee.setDesignation("Manager");
employee.setContactNumber("+919999988822");
employee.setEmailId("abc@test.com");
employee.setMaritalStatus("married");
employee.setGender("female");
// Create JAXB Context
JAXBContext context = JAXBContext.newInstance(Employee.class);
// Create Marshaller
Marshaller jaxbMarshaller = context.createMarshaller();
// Required formatting
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// Print XML String to Console
StringWriter sw = new StringWriter();
// Write XML to StringWriter
jaxbMarshaller.marshal(employee, sw);
// Verify XML Content
String xmlContent = sw.toString();
System.out.println(xmlContent);
} catch (PropertyException e) {
e.printStackTrace();
} catch (JAXBException e) {
}
}
}
When we run the code above, we may check the console output to verify that we have successfully converted the Java object into XML:
The Marshaller class is responsible for governing the process of serializing Java content trees back into XML data.
I hope this has helped you to understand the use of JAXB Version 3.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
As we know, we can use toJson() to convert the JAVA objects to JSON Payload.
In the below example, I have created a POJO class with the name of EmployeeDetails. This class contains 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;
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;
}
}
Below, will create a JSON payload and pass it as a request body to the Rest API.
@Test
public void createEmployee() throws IOException {
// Just create an object of Pojo class
EmployeeDetails emp = new EmployeeDetails();
emp.setName("GsonTest");
emp.setSalary(50000);
emp.setAge(25);
// Converting a Java class object to a JSON payload as string using Gson
Gson builder = new GsonBuilder().setPrettyPrinting().create();
String employeePrettyJsonPayload = builder.toJson(emp);
System.out.println("Request");
System.out.println(employeePrettyJsonPayload);
System.out.println("=========================================");
System.out.println("Response");
// GIVEN
given()
.baseUri("http://dummy.restapiexample.com/api")
.contentType(ContentType.JSON).body(emp)
// WHEN
.when()
.post("/v1/create")
// THEN
.then()
.assertThat().statusCode(200)
.body("status", equalTo("success"))
.body("data.name", equalTo("GsonTest"))
.body("data.salary", equalTo(50000))
.body("data.age", equalTo(25))
.body("message", equalTo("Successfully! Record has been added."))
.log().body();
}
}
Output
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
The previous tutorials explain how to use JAXB(Java Architecture for XML Binding) to parse XML documents to Java objects and vice versa. This is also called Marshalling and Unmarshalling.
This tutorial explains @XmlElementWrapper Annotation.
Configure the Java compiler level to be at least 11 and add the JAXB dependencies to the pom file.
@XmlElementWrapper generates a wrapper element around XML representation. This is primarily intended to be used to produce a wrapper XML element around collections.
This annotation can be used with the following annotations – XmlElement, XmlElements, XmlElementRef, XmlElementRefs, XmlJavaTypeAdapter.
@XmlElementWrapper and @XmlElement (Wrapped collection)
Let us understand this with the help of an example shown below.
@XmlRootElement(name = "CustomerDetails")
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
private int id;
private String name;
private int yearOfBirth;
private String emailId;
private String streetAddress;
private String postcode;
@XmlElementWrapper(name = "emergencyContacts")
@XmlElement(name = "Contact")
private List<String> emergencyContacts;
public Customer() {
super();
}
public Customer(int id, String name, int yearOfBirth, String emailId, String streetAddress, String postcode,
List<String> emergencyContacts) {
super();
this.id = id;
this.name = name;
this.yearOfBirth = yearOfBirth;
this.emailId = emailId;
this.streetAddress = streetAddress;
this.postcode = postcode;
this.emergencyContacts = emergencyContacts;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getYearOfBirth() {
return yearOfBirth;
}
public void setYearOfBirth(int yearOfBirth) {
this.yearOfBirth = yearOfBirth;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public List<String> getEmergencyContacts() {
return emergencyContacts;
}
public void setEmergencyContacts(List<String> emergencyContacts) {
this.emergencyContacts = emergencyContacts;
}
}
Now, let us create a Test to convert these 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.
This tutorial explains how to use JAXB (Java Architecture for XML Binding) to convert Java Objects to XML documents.
JAXB provides a fast and convenient way to marshal (write) Java Objects into XML and un-marshal (read) XML into Java Objects. It supports a binding framework that maps XML elements and attributes to Java fields and properties using Java annotations.
With Java releases lower than Java 11, JAXB was part of the JVM and you could use it directly without defining additional libraries.
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.
When we run the code above, we may check the console output to verify that we have successfully converted Java object to XML:
By default, the Marshaller uses UTF-8 encoding when generating XML data.
The javax.xml.bind.JAXBContext class provides a client’s entry point to JAXB API. By default, JAXB does not format the XML document. This saves space and prevents that any white-space may accidentally be interpreted as significant.
To have JAXB format the output, we simply set the Marshaller.JAXB_FORMATTED_OUTPUT property to true on the Marshaller. The marshal method uses an object and an output file where to store the generated XML as parameters.
You can see that we have used JAXB Annotations like @XMLRootElement are changed from Employee to EmployeeDetails.
@XMLElement has set the element name to GrossSalary from Salary.
The below example is the short way of writing the same test and saving XML. We need to add a constructor in the POJO class so that we can set the values to the variables through the Constructor.
@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;
private double salary;
private String designation;
private String contactNumber;
private String emailId;
private String gender;
private String maritalStatus;
public Employee() {
super();
}
public Employee(String firstName, String lastName, int age, double salary, String designation, String contactNumber,
String emailId, String gender, String maritalStatus) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
@XmlElement(name = "GrossSalary")
this.salary = salary;
this.designation = designation;
this.contactNumber = contactNumber;
this.emailId = emailId;
this.gender = gender;
this.maritalStatus = 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;
}
@Override
public String toString() {
return "Employee [FirstName=" + firstName + ", LastName=" + lastName + ", Age=" + age + ", Salary=" + salary
+ ", Designation=" + designation + ", ContactNumber=" + contactNumber + ", EmailId=" + emailId
+ ", Gender=" + gender + ", MaritalStatus=" + maritalStatus + "]";
}
}
The below JAXB example for XML marshalling convert Java objects into an XML.
@Test
public void serializationTest2() {
try {
Employee employee = new Employee("Thomas", "Pawsey", 35, 100000, "Director", "+919999988822","Test@test.com", "married", "female");
// Create JAXB Context
JAXBContext context = JAXBContext.newInstance(Employee.class);
// Create Marshaller
Marshaller jaxbMarshaller = context.createMarshaller();
// Required formatting
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// Write XML to StringWriter
StringWriter writer = new StringWriter();
jaxbMarshaller.marshal(employee, writer);
// Convert XML to String
String xmlContent = writer.toString();
System.out.println(xmlContent);
// Save the file
String userDir = System.getProperty("user.dir");
jaxbMarshaller.marshal(employee, new File(userDir + "\\src\\test\\resources\\JAXB_XML.xml"));
} catch (PropertyException e) {
e.printStackTrace();
} catch (JAXBException e) {
}
}
}
When we run the code above, we may check the console output to verify that we have successfully converted Java object to XML:
The XML is saved under src/test/resources. To see this file, after the execution of the test, you need to refresh the project.
Similarly, we can unmarshal an XML to Java Objects in the next tutorial.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
The Jackson XML module adds some additional support for XML-specific features, just like JSON has some additional features. These annotations allow us to control the XML namespace and local name for elements, including the root element, whether a field is rendered in an element or as plain text, whether the content of an element is rendered in a CData wrapper, and whether a collection should use a wrapper element or not.
We need to add Jackson XML dependency to the project.
It is used to define the name of the root element used for the root-level object when serialized, which normally uses the name of the type (class). This can only adjust the Namespace and Local name – since the root element can never be serialized as an attribute.
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 to_deserialize.xml with the following contents:
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();
}
}
}
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.
The previous tutorials have explained the conversion of Java Objects to JSON payload and vice versa, i.e. conversion of JSON payload to Java Objects using Jackson API.
This tutorial explains parsing the XML document to Java objects using Jackson API.
To parse the above XML, we will use the Jackson library. Use the latest Jackson library.
We will create an XML from POJO and vice versa now, which is generally called serialization and deserialization using Jackson APIs.
XmlMapper is a subclass of ObjectMapper which is used in JSON serialization. However, it adds some XML-specific tweaks to the parent class.
XmlMapper xmlMapper = new XmlMapper();
We can now look at how to use it to do the actual serialization. Let’s create a Java class first:
Below is the sample code of the Employee table, which contains the data members needed for Employee XML and their corresponding getter and setter methods.
public class Employee {
// 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;
}
}
Writing XML is done using the various writeValue() methods that Jackson exposes.
public class EmployeeXMLTest {
@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 XML
XmlMapper xmlMapper = new XmlMapper();
try {
String employeeXml = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(employeeXml);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
Here, In this new structure, we have introduced a nested nameelement as well as contactdetails element which is further nested to emergencyDetails elements. With our current code, we cannot extract or create the new nested section. So, along with creating a POJO class for Employees, will create a POJO class for name, contactDetails, and emergencyDetails.
Employees
public class Employees {
Name name;
ContactDetails contactdetails;
private int age;
private double salary;
private String designation;
private String emailId;
private String gender;
private String maritalStatus;
// Getter and setter methods
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public ContactDetails getContactdetails() {
return contactdetails;
}
public void setContactdetails(ContactDetails contactdetails) {
this.contactdetails = contactdetails;
}
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 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;
}
}
Name
public class Name {
private String firtsname;
private String middlename;
private String lastname;
public String getFirtsname() {
return firtsname;
}
public void setFirtsname(String firtsname) {
this.firtsname = firtsname;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
ContactDetails -As you can see that EmergencyDetails element which contains emergency_no1, emergency_no2, and emergency_no3 are nested within ContactDetails, so we have created a separate POJO class for EmergencyDetails.
public class ContactDetails {
private String deskNumber;
private String mobileNumber;
EmergencyDetails emergencyDetails;
public EmergencyDetails getEmergencyDetails() {
return emergencyDetails;
}
public void setEmergencyDetails(EmergencyDetails emergencyDetails) {
this.emergencyDetails = emergencyDetails;
}
public String getDeskNumber() {
return deskNumber;
}
public void setDeskNumber(String deskNumber) {
this.deskNumber = deskNumber;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
}
EmergencyDetails
public class EmergencyDetails {
private String emergency_no1;
private String emergency_no2;
private String emergency_no3;
public String getEmergency_no1() {
return emergency_no1;
}
public void setEmergency_no1(String emergency_no1) {
this.emergency_no1 = emergency_no1;
}
public String getEmergency_no2() {
return emergency_no2;
}
public void setEmergency_no2(String emergency_no2) {
this.emergency_no2 = emergency_no2;
}
public String getEmergency_no3() {
return emergency_no3;
}
public void setEmergency_no3(String emergency_no3) {
this.emergency_no3 = emergency_no3;
}
}
Next, we create our serializeToXML() method:
public class XmlSerializationDemo {
@Test
public void serializationXML() throws JsonProcessingException {
Employees employee = new Employees();
Name empname = new Name();
empname.setFirtsname("John");
empname.setMiddlename("Dave");
empname.setLastname("William");
employee.setName(empname);
employee.setAge(30);
employee.setSalary(75000);
employee.setDesignation("Manager");
ContactDetails contdetails = new ContactDetails();
contdetails.setDeskNumber("00-428507");
contdetails.setMobileNumber("+917823561231");
EmergencyDetails emergency = new EmergencyDetails();
emergency.setEmergency_no1("+91 1212898920");
emergency.setEmergency_no2("+91 9997722123");
emergency.setEmergency_no3("+91 8023881245");
contdetails.setEmergencyDetails(emergency);
employee.setContactdetails(contdetails);
employee.setEmailId("abc@test.com");
employee.setMaritalStatus("married");
employee.setGender("female");
XmlMapper xmlMapper = new XmlMapper();
try {
String employeeXml = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(employeeXml);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//To save the XML in a file and place under the project
String userDir = System.getProperty("user.dir");
try {
xmlMapper.writerWithDefaultPrettyPrinter()
.writeValue(new File(userDir + "\\src\\test\\resources\\NestedXMLExample.xml"), employee);
} catch (StreamWriteException e) {
e.printStackTrace();
} catch (DatabindException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
The file is saved under src/test/resources as NestedXMLExample.
There is another way to do the same job of converting Java Object to a complex XML, but which looks more sophisticated and less a number of lines of code.
I’ll use the same complex XML structure.
In this method, we will create a default constructor as well as a parametrized Constructor to pass the arguments for each POJO Class.
Employee
public class Employees {
Name name;
ContactDetails contactdetails;
private int age;
private double salary;
private String designation;
private String emailId;
private String gender;
private String maritalStatus;
public Employees() {
super();
}
public Employees(Name name, ContactDetails contactdetails, int age, double salary, String designation,
String emailId, String gender, String maritalStatus) {
this.name = name;
this.contactdetails = contactdetails;
this.age = age;
this.salary = salary;
this.designation = designation;
this.emailId = emailId;
this.gender = gender;
this.maritalStatus = maritalStatus;
}
// Getter and setter methods
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public ContactDetails getContactdetails() {
return contactdetails;
}
public void setContactdetails(ContactDetails contactdetails) {
this.contactdetails = contactdetails;
}
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 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;
}
}
Name
public class Name {
private String firtsname;
private String middlename;
private String lastname;
public Name() {
super();
}
public Name(String firtsname, String middlename, String lastname) {
super();
this.firtsname = firtsname;
this.middlename = middlename;
this.lastname = lastname;
}
public String getFirtsname() {
return firtsname;
}
public void setFirtsname(String firtsname) {
this.firtsname = firtsname;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
ContactDetails
public class ContactDetails {
private String deskNumber;
private String mobileNumber;
EmergencyDetails emergencyDetails;
public ContactDetails() {
super();
}
public ContactDetails(String deskNumber, String mobileNumber, EmergencyDetails emergencyDetails) {
super();
this.deskNumber = deskNumber;
this.mobileNumber = mobileNumber;
this.emergencyDetails = emergencyDetails;
}
public EmergencyDetails getEmergencyDetails() {
return emergencyDetails;
}
public void setEmergencyDetails(EmergencyDetails emergencyDetails) {
this.emergencyDetails = emergencyDetails;
}
public String getDeskNumber() {
return deskNumber;
}
public void setDeskNumber(String deskNumber) {
this.deskNumber = deskNumber;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
}
EmergencyDetails
public class EmergencyDetails {
private String emergency_no1;
private String emergency_no2;
private String emergency_no3;
public EmergencyDetails() {
super();
}
public EmergencyDetails(String emergency_no1, String emergency_no2, String emergency_no3) {
super();
this.emergency_no1 = emergency_no1;
this.emergency_no2 = emergency_no2;
this.emergency_no3 = emergency_no3;
}
public String getEmergency_no1() {
return emergency_no1;
}
public void setEmergency_no1(String emergency_no1) {
this.emergency_no1 = emergency_no1;
}
public String getEmergency_no2() {
return emergency_no2;
}
public void setEmergency_no2(String emergency_no2) {
this.emergency_no2 = emergency_no2;
}
public String getEmergency_no3() {
return emergency_no3;
}
public void setEmergency_no3(String emergency_no3) {
this.emergency_no3 = emergency_no3;
}
}
Now, let us create a Serialization Test
public class XmlSerializationDemo2 {
@Test
public void serializationTest() {
try {
EmergencyDetails emergency = new EmergencyDetails("+91 894132345", "+91 8888221102", "+91 7223156288");
ContactDetails contdetails = new ContactDetails("00-428507", "+917823561231", emergency);
Name empname = new Name("Trina", "Sophia", "William");
// Converting a Java class object to a XML
XmlMapper xmlMapper = new XmlMapper();
String xmlString = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Employees(empname,
contdetails, 35, 100000.00, "Director", "trina@test.com", "female", "married"));
System.out.println(xmlString);
// write XML string to file
String userDir = System.getProperty("user.dir");
File xmlOutput = new File(userDir + "\\src\\test\\resources\\XMLExample.xml");
FileWriter fileWriter = new FileWriter(xmlOutput);
fileWriter.write(xmlString);
fileWriter.close();
} catch (
JsonProcessingException e) {
} catch (IOException e) {
}
}
}
Output
The newly created XML file is saved under src/test/resources as shown in the below image.
We have successfully serialized our Java object into XML and written it into an XML file.
In our serializationTest() function, we create an XmlMapper object, which is a child class to the ObjectMapper class used in JSON serialization. This class converts our Java Object into an XML output that we can now write to a file.
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.
Let us create a class called Employee with field name exactly (case-sensitive) the same as node names in above JSON string because with 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("########################################################");
}
Output
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("########################################################");
}
}
Output
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!