Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LocalDateTime with JAXB

Tags:

java

time

jaxb

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?

like image 372
hfhc2 Avatar asked Jan 28 '15 10:01

hfhc2


2 Answers

What you have should work. One of the following may be wrong:

  1. Since you have specified the @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?
  2. It is also possible that your package-info.java file is not being compiled.
like image 147
bdoughan Avatar answered Sep 29 '22 04:09

bdoughan


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.

like image 32
Fred Danna Avatar answered Sep 29 '22 04:09

Fred Danna