Can JAXB handle java.time objects?

后端 未结 2 976
我在风中等你
我在风中等你 2020-12-05 18:33

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.ti

2条回答
  •  甜味超标
    2020-12-05 18:53

    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:

    
        com.addicticks.oss
        jtexttime
         ... latest ...
    
    

    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.

提交回复
热议问题