首頁  >  文章  >  Java  >  在Java中使用Jackson函式庫將XML轉換為POJO?

在Java中使用Jackson函式庫將XML轉換為POJO?

WBOY
WBOY轉載
2023-08-30 10:21:06983瀏覽

在Java中使用Jackson函式庫將XML轉換為POJO?

##JSON Jackson 是一個 Java 函式庫。它具有非常強大的資料綁定功能,並提供了一個將自訂java物件序列化為JSON以及將JSON反序列化回Java物件的框架。我們也可以使用 XmlMapper 類別的 readValue() 方法將 XML 格式轉換為 POJO 物件Syntax

<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刪除