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

Convert XML to POJO using Jackson library in Java?

WBOY
WBOYforward
2023-08-30 10:21:06936browse

Convert XML to POJO using 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

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

Example

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

输出

<strong>Person[ firstName = Adithya, lastName = Jai, address = Bangalore ]</strong>

The above is the detailed content of Convert XML to POJO 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