我有一个Response
包含一些基本属性和通配符的类 Collection<?>
.
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Response {
private String approved;
private String errorCode;
@XmlAnyElement(lax = true)
private Collection<?> collection;
public Response() {
}
public Response(String approved, Collection<?> collection) {
this.approved = approved;
this.collection = collection;
}
public String getApproved() {
return approved;
}
public String getErrorCode() {
return errorCode;
}
public Collection<?> getCollection() {
return collection;
}
}
这个集合可以包含多种类型,例如这个类型:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {
private BigDecimal amount;
private String transactionId;
public Transaction(BigDecimal amount, String transactionId ) {
super();
this.amount = amount;
this.transactionId = transactionId ;
}
public Transaction() {
super();
}
public BigDecimal getAmount() {
return amount;
}
public String getTransactionId() {
return transactionId;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
}
序列化 Response
时类,我得到这个 XML。
<?xml version="1.0" encoding="UTF-8"?>
<response>
<approved>00</approved>
<errorCode></errorCode>
<transaction>
<amount>500.00</amount>
<transactionId>pgka3902</transactionId>
</transaction>
<transaction>
<amount>201.05</amount>
<transactionId>abcd3020</transactionId>
</transaction>
</response>
添加@XmlElementWrapper
包裹<transaction>
<collection>
中的元素这仍然是 Not Acceptable 。 我需要将包装器命名为集合中实际类型的复数。例如,上面的xml应该是:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<approved>00</approved>
<errorCode />
<transactions>
<transaction>
<amount>500.00</amount>
<transactionId>pgka3902</transactionId>
</transaction>
<transaction>
<amount>201.05</amount>
<transactionId>abcd3020</transactionId>
</transaction>
</transactions>
</response>
可以用 JAXB 来做到这一点吗?我正在使用 Eclipselink Moxy 实现。
最佳答案
您可以将其更改为Object
,而不是使用Response
保存Collection
。然后,您可以为每种集合类型设置不同的类。
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Transactions {
@XmlElement(name="transaction")
private List<Transaction> transactions;
}
关于java - Collection<?> 将元素包装在 JAXB 中实际类型的复数名称中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26844411/