首页 >Java >java教程 >在Java中使用Jackson库将XML转换为POJO?

在Java中使用Jackson库将XML转换为POJO?

WBOY
WBOY转载
2023-08-30 10:21:061034浏览

在Java中使用Jackson库将XML转换为POJO?

JSON Jackson是一个 Java 库。它具有非常强大的数据绑定功能,并提供了一个将自定义java对象序列化为JSON以及将JSON反序列化回Java对象的框架。我们还可以使用XmlMapper类的readValue()方法将XML格式转换为POJO对象

语法

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

示例

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>

以上是在Java中使用Jackson库将XML转换为POJO?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除