本文介绍了使用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 JAXBElements:
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的动态标记名称
发布评论