Convert POJO to XML using the Jackson library in Java?


A Jackson is a Java-based library and it can be useful to convert Java objects to JSON and JSON to Java Object. A Jackson API is faster than other API, needs less memory area and is good for the large objects. We convert a POJO to XML format using the writeValueAsString() method of XmlMapper class and we need to pass the corresponding POJO instance as an argument to this method.

Syntax

public String writeValueAsString(Object value) throws JsonProcessingException

Example

import com.fasterxml.jackson.dataformat.xml.*;

public class POJOToXmlTest {
   public static void main(String args[]) throws Exception {
      try {
         XmlMapper xmlMapper = new XmlMapper();
         Person pojo = new Person();
         pojo.setFirstName("Raja");
         pojo.setLastName("Ramesh");
         pojo.setAddress("Hyderabad");

         String xml = xmlMapper.writeValueAsString(pojo);
         System.out.println(xml);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

// Person class
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;
   }
}

Output

<Person xmlns="">
   <firstName>Raja</firstName>
   <lastName>Ramesh</lastName>
   <address>Hyderabad</address>
</Person>
raja
Published on 09-Oct-2019 11:51:24
Advertisements