Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can JAXB handle java.time objects?

Tags:

I know JAXB (Java Architecture for XML Binding) can marshal/unmarshal java.util.Date objects as seen in this answer by Blaise Doughan.

But what about the new java.time package objects in Java 8, such as ZonedDateTime? Has JAXB been updated to handle this newly built-in data type?

like image 509
Basil Bourque Avatar asked Jun 16 '14 19:06

Basil Bourque


2 Answers

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.

like image 59
bdoughan Avatar answered Sep 20 '22 15:09

bdoughan


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.

like image 37
lbruun Avatar answered Sep 18 '22 15:09

lbruun