Convert Java Object to XML using Jackson Library


Post Banner

To convert a Java Object into XML we can make use of the Jackson Library, make sure to add the dependency in your project first,

Gradle:
implementation group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.13.4'
Maven:
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.13.4</version>
</dependency>

Convert Java Object to XML (Pojo to XML)

Employee.java
public class Employee {

    String empName;
    int empAge;
    String empDept;

    public Employee(String empName, int empAge, String empDept) {
        this.empName = empName;
        this.empAge = empAge;
        this.empDept = empDept;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public int getEmpAge() {
        return empAge;
    }

    public void setEmpAge(int empAge) {
        this.empAge = empAge;
    }

    public String getEmpDept() {
        return empDept;
    }

    public void setEmpDept(String empDept) {
        this.empDept = empDept;
    }
}
JavaObjectToXML.java
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.io.IOException;

public class JavaObjectToXML {

    public static void main(String[] args) {
        try {

            Employee emp = new Employee("Andy",45,"Insurance");
            XmlMapper xmlMapper = new XmlMapper();
            String xmlString = xmlMapper.writeValueAsString(emp);
            System.out.println(xmlString);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Output:
<Employee><empName>Andy</empName><empAge>45</empAge><empDept>Insurance</empDept></Employee>


Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.