Home  >  Article  >  Java  >  Convert POJO to XML using Jackson library in Java?

Convert POJO to XML using Jackson library in Java?

王林
王林forward
2023-09-18 14:21:031238browse

Convert POJO to XML using Jackson library in Java?

Jackson is a Java-based library that is useful for converting Java objects to JSON and JSON to Java objects. Jackson API Faster than other APIs, requires less memory area, and is suitable for large objects. We use the writeValueAsString() method of the XmlMapper class to convert POJO to XML format, and the corresponding POJO instance needs to be passed as a parameter 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>

The above is the detailed content of Convert POJO to XML using Jackson library in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete