Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

java - Dynamic tag names with JAXB

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

I need to generate an XML response which looks like this:

 <map>
   <2010-04>24</2010-04>
   <2010-05>45</2010-05>
 </map>

What is the best way to generate dynamic tag names with JAXB?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

This approach is ugly, but not uglier than the XML it produces.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...