在Java中使用Jackson库将XML转换为POJO?
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>
以上就是在Java中使用Jackson库将XML转换为POJO?的详细内容,更多请关注其它相关文章!