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>

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap