Ich baue eine Reihe von verknüpften Klassen, deren Instanzen ich in XML marshall werden soll, damit ich sie in einer Datei speichern und später wieder einlesen kann.Marshalling LocalDate mit JAXB
Derzeit Ich verwende den folgenden Code als Testfall:
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);
}
}
Die XML-Ausgabe ist:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<wrapperTest>
<startDate/>
</wrapperTest>
Gibt es einen Grund, warum die startDate
Element leer ist? Ich möchte, dass es die Zeichenfolgendarstellung des Datums enthält (d. H. toString()
). Muss ich etwas eigenen Code schreiben, um dies zu tun?
Die Ausgabe von java -version
ist:
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)
scheint genau das zu tun, was ich will - danke! – pwaring