Reputation: 1646
I have a question for storing Datetime into Jaxb. Currently I have this:
XML:
<reconcile>
<start_date>2018-04-08T11:02:44</start_date>
<end_date>2018-04-08T11:02:44</end_date>
<page>1</page>
</reconcile>
JaxB Object:
@XmlElement(name = "start_date")
public Date start_date;
@XmlElement(name = "end_date")
public Date end_date;
@XmlElement(name = "page")
Should I use String for start_date and end_date or I need convert the String 2018-04-08 11:02:44
before I use JAXB? Can you share what is the best practice?
Upvotes: 1
Views: 323
Reputation: 159114
Added the JAXB for java.time
from https://github.com/jaxb-java-time-adapters/jaxb-java-time-adapters#releases
Then annotate like this:
@XmlRootElement
public class Reconcile {
@XmlElement(name = "start_date")
@XmlJavaTypeAdapter(LocalDateTimeXmlAdapter.class)
public LocalDateTime start_date;
@XmlElement(name = "end_date")
@XmlJavaTypeAdapter(LocalDateTimeXmlAdapter.class)
public LocalDateTime end_date;
@XmlElement(name = "page")
public int page;
}
Test
Reconcile reconcile = new Reconcile();
reconcile.start_date = LocalDateTime.of(2018, 4, 8, 11, 2, 44);
reconcile.end_date = LocalDateTime.of(2018, 11, 8, 11, 2, 44);
reconcile.page = 1;
JAXBContext jaxbContext = JAXBContext.newInstance(Reconcile.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(reconcile, System.out);
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<reconcile>
<start_date>2018-04-08T11:02:44</start_date>
<end_date>2018-11-08T11:02:44</end_date>
<page>1</page>
</reconcile>
Upvotes: 2