简体   繁体   中英

I want to convert an Object with a java.time.Localdate (JSR-310) to XML via JAXB but the output is wrong

I want to convert an Object with a java.time.Localdate (JSR-310) and a property wrapping a Localdate to XML via JAXB but the output is wrong.

public <T> void printPdf(T obj) {
    // create xml
    JAXBContext context = JAXBContext.newInstance(obj.getClass());
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    StringWriter outWriter = new StringWriter();
    StreamResult result = new StreamResult(outWriter);
    m.marshal(obj, result);

    StringBuffer sb = outWriter.getBuffer();
    String finalstring = sb.toString();
    System.out.println(finalstring);
}

This is the Object:

@XmlRootElement
public class Invoice implements Validateable {
    private LocalDate date = LocalDate.now();
    private ObjectProperty<LocalDate> dueDate = new SimpleObjectProperty<LocalDate>(
            LocalDate.now().plusDays(20));
    // ========================================================================
    // date
    // ========================================================================
    public LocalDate getDate() {
        return date;
    }
    public void setDate(LocalDate date) {
        this.date = date;
    }
    // ========================================================================
    // companyName
    // ========================================================================
    public LocalDate getDueDate() {
        return this.dueDate.get();
    }
    public void setDueDate(LocalDate duedate) {
        this.dueDate.set(duedate);
    }
    public final ObjectProperty<LocalDate> dueDateProperty() {
        return dueDate;
    }
}

This is the XML output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<invoice>
    <date/>
    <dueDate/>
</invoice>

How can I convert this properly? I'm not stuck to use JAXB if there is something better out there.

You can use a JAXB XmlAdapter to control how the JSR-310 objects are converted to/from XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM