Skip to content
On this page

Using Jackson

Previously, we introduced two standard XML parsing interfaces: DOM and SAX. However, both are not very intuitive to use.

Let's examine the structure of the following XML document:

xml
<?xml version="1.0" encoding="UTF-8" ?>
<book id="1">
    <name>Java核心技术</name>
    <author>Cay S. Horstmann</author>
    <isbn lang="CN">1234567</isbn>
    <tags>
        <tag>Java</tag>
        <tag>Network</tag>
    </tags>
    <pubDate/>
</book>

We notice that it can be easily mapped to a predefined JavaBean:

java
public class Book {
    public long id;
    public String name;
    public String author;
    public String isbn;
    public List<String> tags;
    public String pubDate;
}

If we can directly parse the XML document into a JavaBean, it would be much simpler than using DOM or SAX.

Fortunately, an open-source third-party library called Jackson can easily convert XML into a JavaBean. To use Jackson, add the following Maven dependency:

xml
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.10.1</version>
</dependency>

After defining the JavaBean, the XML can be parsed with just a few lines of code:

java
InputStream input = Main.class.getResourceAsStream("/book.xml");
JacksonXmlModule module = new JacksonXmlModule();
XmlMapper mapper = new XmlMapper(module);
Book book = mapper.readValue(input, Book.class);
System.out.println(book.id);
System.out.println(book.name);
System.out.println(book.author);
System.out.println(book.isbn);
System.out.println(book.tags);
System.out.println(book.pubDate);

Notice that XmlMapper is the core object that we need to create. It can use readValue(InputStream, Class) to read the XML and return a JavaBean directly. Running the above code, we can easily access the data from the Book object:

1
Core Java
Cay S. Horstmann
1234567
[Java, Network]
null

If the data format to be parsed is not one of Jackson's built-in standard formats, a custom parser can be configured to tell Jackson how to parse it. For more details, you can refer to the Jackson official documentation.

Exercise

Use Jackson to parse XML.

Summary

Using Jackson to parse XML allows you to directly convert XML into a JavaBean, making it very convenient.

Using Jackson has loaded