Sto costruendo una serie di classi collegate le cui istanze voglio essere in grado di eseguire il marshalling in XML, così posso salvarle in un file e leggerle di nuovo in seguito.Marshalling LocalDate con JAXB
Attualmente sto usando il seguente codice come un banco di prova:
import javax.xml.bind.annotation.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.time.LocalDate;
public class LocalDateExample
{
@XmlRootElement
private static class WrapperTest {
public LocalDate startDate;
}
public static void main(String[] args) throws JAXBException
{
WrapperTest wt = new WrapperTest();
LocalDate ld = LocalDate.of(2016, 3, 1);
wt.startDate = ld;
marshall(wt);
}
public static void marshall(Object jaxbObject) throws JAXBException
{
JAXBContext context = JAXBContext.newInstance(jaxbObject.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(jaxbObject, System.out);
}
}
L'output XML è:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<wrapperTest>
<startDate/>
</wrapperTest>
C'è un motivo per cui l'elemento startDate
è vuota? Mi piacerebbe che contenga la rappresentazione in formato stringa della data (ad esempio toString()
). Devo scrivere un codice mio per poterlo fare?
L'uscita del java -version
è:
openjdk version "1.8.0_66-internal"
OpenJDK Runtime Environment (build 1.8.0_66-internal-b17)
OpenJDK 64-Bit Server VM (build 25.66-b17, mixed mode)
sembra fare esattamente quello che voglio - grazie! – pwaring