Can JAXB handle java.time objects?
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.
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.