Convert XML to POJO using the Jackson library in Java?


The JSON Jackson is a library for Java. It has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. We can also convert an XML format to the POJO object using the readValue() method of the XmlMapper class.

Syntax

public <T> T readValue(XMLStreamReader r, Class<T> valueType) throws IOException

Example

import com.fasterxml.jackson.dataformat.xml.*;
public class XMLToPOJOTest {
   public static void main(String args[]) throws Exception {
      try {
         XmlMapper xmlMapper = new XmlMapper();
         Person pojo = xmlMapper.readValue(getXmlString(), Person.class);
         System.out.println(pojo);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
   private static String getXmlString() {
      return "<person> <firstName>Adithya</firstName>"
                    + "<lastName>Jai</lastName>"
                    + "<address>Bangalore</address>" + "</person>";
   }
}
// Person class (POJO)
class Person {
   private String firstName;
   private String lastName;
   private String address;
   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 getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   public String toString() {
      return "Person[ " +
             "firstName = " + firstName +
             ", lastName = " + lastName +
             ", address = " + address +
             " ]";
   }
}

Output

Person[ firstName = Adithya, lastName = Jai, address = Bangalore ]

Updated on: 14-Feb-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements