
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
public <T> T readValue(XMLStreamReader r, Class<T> valueType) throws IOException
Example
import com.fasterxml.jackson.dataformat.xml.*; public class XMLToPOJOTest { public static void main(String args[]) throws Exception { try { XmlMapper xmlMapper = new XmlMapper(); Person pojo = xmlMapper.readValue(getXmlString(), Person.class); System.out.println(pojo); } catch(Exception e) { e.printStackTrace(); } } private static String getXmlString() { return "<person> <firstName>Adithya</firstName>" + "<lastName>Jai</lastName>" + "<address>Bangalore</address>" + "</person>"; } } // Person class (POJO) 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 + " ]"; } }
Output
Person[ firstName = Adithya, lastName = Jai, address = Bangalore ]
Advertisements