How to use java.time.LocalDateTime in your JAXB Bindings
I recently had a issue with some code that was using java 1.7 and I moved it over to java 1.8. Basically the issue was that the code was still binding the dateTime element to java “Calendar” class. Java 1.8 introduced java.time.* classes which I used to write POJO code interfacing with the JAXB classes.
What I like about the java.time.* classes is that they conform with ISO-8601 formats, a requirement I added to a current project I am working on.
So I had to do two things
1. Create a custom adapter for java.time.<time_implementation>
2. Update my global.xjb to create the binding to the xml element
Here is my custom adapter, debug statements were for me to verify everything was working properly in the system:
package com.jaysfables.xmlutils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
@SuppressWarnings({ "rawtypes", "restriction" })
public class LocalDateTimeAdapter extends XmlAdapter{
@Override
public LocalDateTime unmarshal(Object v) throws Exception {
System.out.println("DEBUG: unmarshal localdatetime: " + (String) v);
return LocalDateTime.parse((String) v);
}
@Override
public Object marshal(Object v) throws Exception {
System.out.println("DEBUG: marshal localdatetime: " + ((LocalDateTime)v).toString());
if (v != null) {
return ((LocalDateTime)v).toString();
} else {
return null;
}
}
}
Next was to update the global.xjb file to point to the custom adapter:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings version="2.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
jaxb:extensionBindingPrefixes="xjc">
<jaxb:globalBindings>
<xjc:simple />
<xjc:serializable uid="-1" />
<xjc:javaType adapter="com.jaysfables.xmlutils.LocalDateTimeAdapter" name="java.time.LocalDateTime"
xmlType="xs:dateTime" />
</jaxb:globalBindings>
</jaxb:bindings>
did a maven rebuild and everything worked flawlessly.