1

我必须查询返回包含一张发票或发票列表的 XML 文件的多个 URL(我知道哪些 URL 将返回一个列表,哪些将只返回一个发票)。

单张发票格式(简体):

<?xml version="1.0" encoding="UTF-8"?>
  <invoice>
    <invoice-id>1</invoice-id>
</invoice>

发票清单的格式:

<?xml version="1.0" encoding="UTF-8"?>
<invoices>
  <invoice>
    <invoice-id>1</invoice-id>
  </invoice>
  <invoice>
    <invoice-id>2</invoice-id>
  </invoice>
</invoices>

Jersey 可以自动处理第一个 xml 片段并将其转换为 Java 类:

@XmlRootElement
public class Invoice {
    @XmlElement(name="invoice-id")  
    Integer invoiceId;
}

这是通过以下代码完成的:

GenericType<JAXBElement<Invoice>> invoiceType = new GenericType<JAXBElement<Invoice>>() {};
Invoice invoice = (Invoice) resource.path("invoice_simple.xml").accept(MediaType.APPLICATION_XML_TYPE).get(invoiceType).getValue(); 

以上作品。

现在我想要一个 InvoiceList 对象,如下所示:

@XmlRootElement
public class InvoiceList {
    @XmlElementWrapper(name="invoices")
    @XmlElement(name="invoice")
    List<Invoice> invoices; 
}

这是我遇到问题的地方;InvoiceList.invoices 在以下情况下保持为空:

GenericType<JAXBElement<InvoiceList>> invoicesType = new GenericType<JAXBElement<InvoiceList>>() {};
InvoiceList invoices = (InvoiceList) resource.path("invoices_simple.xml").accept(MediaType.APPLICATION_XML_TYPE).get(invoicesType).getValue();      
// now invoices.invoices is still null!

我知道 Jersey/JAXB 可以处理对象列表,但如果顶部元素包含列表,它似乎将不起作用。

所以,我的问题是:如何指示 Jersey 解析包含发票对象列表的 xml 文件?

4

1 回答 1

2

第一个答案是

放在. nillable = true_@XmlElement

@XmlElement(name = "invoice", nillable = true)
List<Invoice> invoices; 

我会这样做。(您不必包装已经包装的集合。)

@XmlRootElement
public class Invoices {

    public List<Invoice> getInvoices() {
        if (invoices == null) {
            invoices = new ArrayList<Invoice>();
        }
        return invoices;
    }

    @XmlElement(name = "invoice", nillable = true)
    private List<Invoice> invoices; 
}

一些 JAX-RS 示例是这样的

@GET
@Path("/invoices")
public Invoices readInvoices() {
    // ...
}

@GET
@Path("/invoices/{invoice_id: \\d+}")
public Invoice readInvoice(@PathParam("invoice_id") final long invoiceId) {
    // ...
}
于 2012-12-16T15:45:34.267 回答