使用JAXB的动态标记名称

编程入门 行业动态 更新时间:2024-10-23 19:28:18
本文介绍了使用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的动态标记名称

本文发布于:2023-11-12 12:39:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581514.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标记   名称   动态   JAXB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!