Can JAXB handle java.time objects?

13,323

Solution 1

In Java SE 8, JAXB has not been updated yet to support the java.time types.

Indeed, there is an issue related to this in the reference implementation.

You need to create and use an XmlAdapter to handle those types. Use an approach similar to that done with Joda-Time as described in this posting, JAXB and Joda-Time: Dates and Times.

You may be able to use this implementation of adapters for java.time.

Solution 2

We couldn't use the library linked in the accepted answer as it glosses over an important detail: In XML Schema date/time values allow the timezone offset to be missing. An adapter must be able to handle this situation. Also, the fact that Java doesn't have a date-only datatype must be supported.

jTextTime library solves this.

The library revolves around the JDK8 OffsetXXX date/time classes as these are the (only) natural equivalent for the XML Schema types date, dateTime and time.

Use like this:

Add dependency:

<dependency>
    <groupId>com.addicticks.oss</groupId>
    <artifactId>jtexttime</artifactId>
    <version> ... latest ...</version>
</dependency>

Annotate your classes:

public class Customer {

    @XmlElement
    @XmlJavaTypeAdapter(OffsetDateTimeXmlAdapter.class)
    @XmlSchemaType(name="dateTime")
    public OffsetDateTime getLastOrderTime() {
        ....
    }

    @XmlElement
    @XmlJavaTypeAdapter(OffsetDateXmlAdapter.class)
    @XmlSchemaType(name="date")
    public OffsetDateTime getDateOfBirth() {   // returns a date-only value
        ....
    }
}

If you don't want to annotate each class individually then you can use package-level annotations as explained here.

If you generate Java classes from XSD files using the xjc tool then this is also explained.

Share:
13,323

Related videos on Youtube

Basil Bourque
Author by

Basil Bourque

SOreadytohelp

Updated on June 18, 2022

Comments