Home > Java > javaTutorial > body text

Convert POJO to XML using Jackson library in Java?

王林
Release: 2023-09-18 14:21:03
forward
1264 people have browsed it

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
Copy after login

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;
   }
}
Copy after login

Output

<Person xmlns="">
   <firstName>Raja</firstName>
   <lastName>Ramesh</lastName>
   <address>Hyderabad</address>
</Person>
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template