Can JAXB handle java.time objects?

2019-01-23 03:24发布

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?

2条回答
Juvenile、少年°
2楼-- · 2019-01-23 03:53

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

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.

查看更多
Ridiculous、
3楼-- · 2019-01-23 03:57

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.

JaxbDateTime library solves this.

If revolves around the JDK8 Offset... 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.jaxb</groupId>
    <artifactId>java8datetime</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 in the README.

Also the README explains how to use if you generate classes from XSD files using xjc tool.

查看更多
登录 后发表回答