我有一个枚举:
@XmlEnum
@XmlRootElement
public enum Product {
POKER("favourite-product-poker"),
SPORTSBOOK("favourite-product-casino"),
CASINO("favourite-product-sportsbook"),
SKILL_GAMES("favourite-product-skill-games");
private static final String COULD_NOT_FIND_PRODUCT = "Could not find product: ";
private String key;
private Product(final String key) {
this.key = key;
}
/**
* @return the key
*/
public String getKey() {
return key;
}
Run Code Online (Sandbox Code Playgroud)
我在这样的REST服务中输出:
GenericEntity<List<Product>> genericEntity = new GenericEntity<List<Product>>(products) {
};
return Response.ok().entity(genericEntity).build();
Run Code Online (Sandbox Code Playgroud)
它输出如下:
<products>
<product>POKER</product>
<product>SPORTSBOOK</product>
<product>CASINO</product>
<product>SKILL_GAMES</product>
</products>
Run Code Online (Sandbox Code Playgroud)
我希望它输出枚举名称(即POKER)和密钥(即"最喜欢的产品 - 扑克").
我尝试了很多不同的方法,包括使用@XmlElement,@ XMLEnumValue和@XmlJavaTypeAdapter,而不是同时使用它们.
有没有人知道如何实现这一点,就像普通的JAXB注释bean一样?
谢谢.
您可以为此创建一个包装对象,例如:
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
@XmlRootElement(name="product")
public class ProductWrapper {
private Product product;
@XmlValue
public Product getValue() {
return product;
}
public void setValue(Product value) {
this.product = value;
}
@XmlAttribute
public String getKey() {
return product.getKey();
}
}
Run Code Online (Sandbox Code Playgroud)
这将对应于以下 XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<product key="favourite-product-poker">POKER</product>
Run Code Online (Sandbox Code Playgroud)
您需要将 ProductWrapper 实例而不是 Product 传递给 JAXB。
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(ProductWrapper.class);
ProductWrapper pw = new ProductWrapper();
pw.setValue(Product.POKER);
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(pw, System.out);
}
}
Run Code Online (Sandbox Code Playgroud)