JAXB +枚举 +显示多个值
我有一个枚举:
@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;
}
我在 REST 服务中输出如下:
GenericEntity<List<Product>> genericEntity = new GenericEntity<List<Product>>(products) {
};
return Response.ok().entity(genericEntity).build();
它输出如下:
<products>
<product>POKER</product>
<product>SPORTSBOOK</product>
<product>CASINO</product>
<product>SKILL_GAMES</product>
</products>
我希望它同时输出枚举名称(即 POKER)和密钥(即“favourite-product-poker”) 。
我尝试了多种不同的方法来执行此操作,包括使用 @XmlElement、@XmlEnumValue 和 @XmlJavaTypeAdapter,但没有同时使用这两种方法。
有谁知道如何实现这一点,就像普通的 JAXB 带注释的 bean 一样?
谢谢。
I have an enum:
@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;
}
that I output in a REST service like so:
GenericEntity<List<Product>> genericEntity = new GenericEntity<List<Product>>(products) {
};
return Response.ok().entity(genericEntity).build();
and it outputs like this:
<products>
<product>POKER</product>
<product>SPORTSBOOK</product>
<product>CASINO</product>
<product>SKILL_GAMES</product>
</products>
I want it to output with both the enum name (i.e, POKER) and the key (i.e, "favourite-product-poker").
I have tried a number of different ways of doing this including using @XmlElement, @XmlEnumValue and @XmlJavaTypeAdapter, without getting both out at the same time.
Does anyone know how to achieve this, as you would for a normal JAXB annotated bean?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以为此创建一个包装器对象,如下所示:
这将对应于以下 XML:
您需要将 ProductWrapper 的实例而不是 Product 传递给 JAXB。
You could create a wrapper object for this, something like:
This would correspond to the following XML:
You would need to pass instances of ProductWrapper to JAXB instead of Product.
您可以使用适配器:
You can use an adapter:
如果您希望像普通对象一样将其序列化为 XML,则需要从枚举值中删除 @XmlEnum。枚举(根据定义)在 XML 中由单个字符串符号表示。例如,这允许将其与 @XmlList 组合以创建高效的、以空格分隔的项目列表。
You need to remove the @XmlEnum from your enum value, if you want it to be serialized into XML like a normal object. An enum (by definition) is represented in the XML by a single string symbol. This allows combining it with @XmlList, for example, to create an efficient, whitespace-separated list of items.