简体   繁体   中英

java - JAXB Null value

Maybe this is a simple request, but I haven't found the way to do it.

I have to build an XML output like these one:

 <person name="Mike">
    <orders id="1">
       <order ido="1"></order>
    </orders>
 </person>

I have to get the values from a query in the db, but in the case that the querys returns no "orders" then the XML have to be like this:

<person name="Mike">
    </orders>
<person>

Is these possible?, I know is kind of strange but is a requirement of the client.

您可以在编组以获取所需的输出之前在Person类上设置Orders的空实例。

I know we have this case in our code often. We define the XML first as an XSD, and then generate the JAXB. To do so, the orders would be 0..1, and then the list inside orders would be 1..n.

If you are just annotating your classes, I think you need to do something like this:

@XmlElement(name = "orders")
protected List<Order> orders;

public List<Order> getOrders() {
    if (orders == null) {
        orders = new ArrayList<Order>();
    }
    return this.orders;
}

This will always return a list. If the list is empty, you should get <orders /> returned.

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