I am trying to use JAXB with fields of the LocalDateTime
type. I wrote an adapter to handle conversion:
public class LocalDateTimeXmlAdapter extends XmlAdapter<String, LocalDateTime> {
@Override
public String marshal(LocalDateTime arg0) throws Exception {
return arg0.toString();
}
@Override
public LocalDateTime unmarshal(String arg) throws Exception {
return LocalDateTime.parse(arg);
}
}
I registered the adapter in package-info.java
like so:
@XmlJavaTypeAdapters({
@XmlJavaTypeAdapter(type=LocalDateTime.class, value=LocalDateTimeXmlAdapter.class)
})
package xml;
import java.time.LocalDateTime;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
This seems to be sufficient according to this page. However, I keep getting the following error:
com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
java.time.LocalDateTime does not have a no-arg default constructor.
I understand the reason for the exception being thrown, but I can hardly add a default constructor to java.time.LocalDateTime
. This seems to be a shortcoming of the class / a strange design decision. Are there any workarounds?
What you have should work. One of the following may be wrong:
@XmlJavaTypeAdapter
at the package level it will only apply to properties on classes in your package called xml
. Is there a class in your model from a different package that has a mapped property of type LocalDateTime
?package-info.java
file is not being compiled.Had same behaviour: IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
.
My pbm was: I have several packages (three) where the package-info.java
file is needed, like shown in the following picture.
I "solved" this pbm by adding a package-info.java
in each of the three directories. Example for package fr.gouv.agriculture.dal.ct.planCharge.metier.dao.charge.xml
:
@XmlJavaTypeAdapter(type = LocalDate.class, value = LocalDateXmlAdapter.class)
package fr.gouv.agriculture.dal.ct.planCharge.metier.dao.charge.xml;
If someone has a better idea than copy/paste into several package-info.java
files, thanks in advance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With