使用JAXB的动态标记名称 [英] Dynamic tag names with JAXB
本文介绍了使用JAXB的动态标记名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Jersey和JAXB构建一个简单的RESTful web服务
我有一个'String'的HashMap到'Integer':
I am using Jersey and JAXB to build a simple RESTful webservice I have a HashMap of 'String' to 'Integer':
2010-04 -> 24
2010-05 -> 45
我需要生成一个XML响应,如下所示:
I need to generate an XML response which looks like this:
<map>
<2010-04>24</2010-04>
<2010-05>45</2010-05>
</map>
使用JAXB生成动态标签名称的最佳方法是什么?
What is the best way to generate dynamic tag names with JAXB?
推荐答案
您可以使用 @XmlAnyElement
-annotated属性并将元素作为返回JAXBElement
s:
You can use an @XmlAnyElement
-annotated property and return the elements as JAXBElement
s:
private Map<String, Integer> months = ...;
@XmlAnyElement
public List<JAXBElement<Integer>> getMonths() {
List<JAXBElement<Integer>> elements = new ArrayList<JAXBElement<Integer>>();
for (Map.Entry<String, Integer> month: months.entrySet())
elements.add(new JAXBElement(new QName(month.getKey()),
Integer.class, month.getValue()));
return elements;
}
这种方法很丑陋,但并不比它产生的XML更丑。
This approach is ugly, but not uglier than the XML it produces.
这篇关于使用JAXB的动态标记名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文