First write simple converter (to Calendar
in this example, but can be easily changed to Joda-Time):
public class XsdDateTimeConverter {
public static Calendar unmarshal(String dateTime) {
final GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(DatatypeConverter.parseDate(dateTime).getTime());
return calendar;
}
public static String marshal(Calendar calendar) {
return DatatypeConverter.printDate(calendar);
}
}
Next you have to introduce your converter to JAXB (xjb
file):
<globalBindings>
<javaType
name="java.util.Calendar"
xmlType="xs:dateTime"
parseMethod="XsdDateTimeConverter.unmarshal"
printMethod="XsdDateTimeConverter.marshal"
/>
<javaType
name="java.util.Calendar"
xmlType="xs:date"
parseMethod="XsdDateTimeConverter.unmarshal"
printMethod="XsdDateTimeConverter.marshal"
/>
</globalBindings>
In the generated JAXB models xjc
produced the following annotation:
@XmlJavaTypeAdapter(Adapter2.class)
@XmlSchemaType(name = "date")
protected Calendar date;
Where Adapter2.class
is a generated adapter that wraps your POJO converter. As you can see Calendar
is used instead of clumsy javax.xml.datatype.XMLGregorianCalendar
. If you adjust this example to Joda-Time, please share it with us.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…