Using LocalDateTime with JAXB

I am trying to use JAXB with fields like LocalDateTime . I wrote an adapter to handle the 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 as follows:

 @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 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, but I can hardly add a default constructor to java.time.LocalDateTime . This seems to be a disadvantage of the class / weird design solution. Are there any workarounds?

+6
source share
2 answers

What you have to work. One of the following may be incorrect:

  • Since you specified @XmlJavaTypeAdapter at the package level, it will only apply to class properties in your package called xml . Is there a class in your model from another package that has a mapped property of type LocalDateTime ?
  • It is also possible that your package-info.java file is not compiling.
+2
source

There was the same behavior: IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions .

My pbm was: I have several packages (three) where the package-info.java file is needed, as shown in the following figure .

I โ€œsolvedโ€ this pbm by adding package-info.java to 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 anyone has a better idea than copying / pasting into multiple package-info.java files, thanks in advance.

+1
source

Source: https://habr.com/ru/post/981659/


All Articles