Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In this tutorial, we’re going to see how to unmarshal date objects with different formats using JAXB.

First, we’ll cover the default schema date format. Then, we’ll explore how to use different formats. We’ll also see how we can handle a common challenge that arises with these techniques.

2. Schema to Java Binding

First, we need to understand the relationship between the XML Schema and Java data types. In particular, we’re interested in the mapping between an XML Schema and Java date objects.

According to the Schema to Java mapping, there are three Schema data types that we need to take into account: xsd:date, xsd:time and xsd:dateTime. As we can see, all of them are mapped to javax.xml.datatype.XMLGregorianCalendar.

We also need to understand the default formats for these XML Schema types. The xsd:date and xsd:time data types have “YYYY-MM-DD” and “hh:mm:ss” formats. The xsd:dateTime format is “YYYY-MM-DDThh:mm:ss” where “T” is a separator indicating the start of the time section.

3. Using the Default Schema Date Format

We’re going to build an example that unmarshals date objects. Let’s focus on the xsd:dateTime data type because it’s a superset of the other types.

Let’s use a simple XML file that describes a book:

<book>
    <title>Book1</title>
    <published>1979-10-21T03:31:12</published>
</book>

We want to map the file to the corresponding Java Book object:

@XmlRootElement(name = "book")
public class Book {

    @XmlElement(name = "title", required = true)
    private String title;

    @XmlElement(name = "published", required = true)
    private XMLGregorianCalendar published;

    @Override
    public String toString() {
        return "[title: " + title + "; published: " + published.toString() + "]";
    }

}

Finally, we need to create a client application that converts the XML data to JAXB-derived Java objects:

public static Book unmarshalDates(InputStream inputFile) 
  throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    return (Book) jaxbUnmarshaller.unmarshal(inputFile);
}

In the above code, we’ve defined a JAXBContext which is the entry-point into the JAXB API. Then, we’ve used a JAXB Unmarshaller on an input stream in order to read our object:

If we run the above code and print the result, we’ll get the following Book object:

[title: Book1; published: 1979-11-28T02:31:32]

We should note that, even though the default mapping for xsd:dateTime is the XMLGregorianCalendar, we could also have used the more common Java types: java.util.Date and java.util.Calendar, according to the JAXB user guide.

4. Using a Custom Date Format

The above example works because we’re using the default schema date format, “YYYY-MM-DDThh:mm:ss”.

But what if we want to use another format like “YYYY-MM-DD hh:mm:ss”, getting rid of the “T” delimiter? If we were to replace the delimiter with a space character in our XML file, the default unmarshalling would fail.

4.1. Building a Custom XmlAdapter

In order to use a different date format, we need to define an XmlAdapter.

Let’s also see how to map the xsd:dateTime type to a java.util.Date object with our custom XmlAdapter:

public class DateAdapter extends XmlAdapter<String, Date> {

    private static final String CUSTOM_FORMAT_STRING = "yyyy-MM-dd HH:mm:ss";

    @Override
    public String marshal(Date v) {
        return new SimpleDateFormat(CUSTOM_FORMAT_STRING).format(v);
    }

    @Override
    public Date unmarshal(String v) throws ParseException {
        return new SimpleDateFormat(CUSTOM_FORMAT_STRING).parse(v);
    }

}

In this adapter, we’ve used SimpleDateFormat to format our date. We need to be careful as the SimpleDateFormat is not thread-safe. To avoid multiple threads experiencing issues with a shared SimpleDateFormat object, we are creating a new one each time we need it.

4.2. The XmlAdapter‘s Internals

As we can see, the XmlAdapter has two type parameters, in this case, String and Date. The first one is the type used inside the XML and is called the value type. In this case, JAXB knows how to convert an XML value into a String. The second one is called the bound type and relates to the value in our Java object.

The objective of an adapter is to convert between the value type and a bound type, in a way that JAXB cannot do by default.

In order to build a custom XmlAdapter, we have to override two methods: XmlAdapter.marshal() and XmlAdapter.unmarshal().

During unmarshalling, the JAXB binding framework first unmarshals the XML representation to a String and then invokes DateAdapter.unmarshal() to adapt the value type to a Date. During marshalling, the JAXB binding framework invokes DateAdapter.marshal() to adapt a Date to String, which is then marshaled to an XML representation.

4.3. Integrating via the JAXB Annotations

The DateAdapter works like a plugin to JAXB and we’re going to attach it to our date field using the @XmlJavaTypeAdapter annotation. The @XmlJavaTypeAdapter annotation specifies the use of an XmlAdapter for custom unmarshalling:

@XmlRootElement(name = "book")
public class BookDateAdapter {

    // same as before

    @XmlElement(name = "published", required = true)
    @XmlJavaTypeAdapter(DateAdapter.class)
    private Date published;

    // same as before

}

We’re also using the standard JAXB annotations: @XmlRootElement and @XmlElement annotations.

Finally, let’s run the new code:

[title: Book1; published: Wed Nov 28 02:31:32 EET 1979]

5. Unmarshalling Dates in Java 8

Java 8 introduced a new Date/Time API. Here, we’re going to focus on the LocalDateTime class which is one of the most commonly used.

5.1. Building a LocalDateTime-based XmlAdapter

By default, JAXB cannot automatically bind an xsd:dateTime value to a LocalDateTime object regardless of the date format. In order to convert an XML Schema date value to or from a LocalDateTime object, we need to define another XmlAdapter similar to the previous one:

public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {

    private DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public String marshal(LocalDateTime dateTime) {
        return dateTime.format(dateFormat);
    }

    @Override
    public LocalDateTime unmarshal(String dateTime) {
        return LocalDateTime.parse(dateTime, dateFormat);
    }

}

In this case, we’ve used a DateTimeFormatter instead of a SimpleDateFormat. The former was introduced in Java 8 and it’s compatible with the new Date/Time API.

Note that the conversion operations can share a DateTimeFormatter object because the DateTimeFormatter is thread-safe.

5.2. Integrating the New Adapter

Now, let’s replace the old adapter with the new one in our Book class and also Date with LocalDateTime:

@XmlRootElement(name = "book")
public class BookLocalDateTimeAdapter {

    // same as before

    @XmlElement(name = "published", required = true)
    @XmlJavaTypeAdapter(LocalDateTimeAdapter.class)
    private LocalDateTime published;

    // same as before

}

If we run the above code, we’ll get the output:

[title: Book1; published: 1979-11-28T02:31:32]

Note that the LocalDateTime.toString() adds the “T” delimiter between date and time.

6. Conclusion

In this tutorial, we explored unmarshalling dates using JAXB.

First, we looked at the XML Schema to Java data type mapping and created an example using the default XML Schema date format.

Next, we learned how to use a custom date format based on a custom XmlAdapter and saw how to handle the thread safety of SimpleDateFormat.

Finally, we leveraged the superior, thread-safe, Java 8 Date/Time API and unmarshalled dates with custom formats.

As always, the source code used in the tutorial is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.