It seems the latest JAX-RS can handle methods returning java.util.List as the XMLRootElement but normal JAXB cannot. I would like to mimic what CXF and Jersey are doing.
In other words I would like to Marshal a List and just like CXF and Jersey do. Normally if you try to marshal a list with JAXB you get the Root Element exception. How do I get around this with out having to make a wrapping object?
EDIT: Thanks for the many answers but I'm very familiar with the @XmlElementWrapper but that does not even come close to simulating what JAX-RS is doing.
JAX-RS does this:
@XmlRootElement(name="dog")
public class Dog {
private String name;
public String getName() { return this.name; }
//Setter also
}
Now if I serialize a list of dogs:
serialize(List<Dog> dogs);
XML should be (what JAX-RS does):
<dogs>
<dog><name>Rascal</name></dog>
</dogs>
So you can see I don't want to have to make a wrapper object for every single domain object.
In JAXB, marshalling involves parsing an XML content object tree and writing out an XML document that is an accurate representation of the original XML document, and is valid with respect the source schema. JAXB can marshal XML data to XML documents, SAX content handlers, and DOM nodes.
JAXB stands for Java Architecture for XML Binding. It provides mechanism to marshal (write) java objects into XML and unmarshal (read) XML into object. Simply, you can say it is used to convert java object into xml and vice-versa.
Marshalling is the process of transforming Java objects into XML documents. Unmarshalling is the process of reading XML documents into Java objects. The JAXBContext class provides the client's entry point to the JAXB API.
Could you not simply add:
@XmlElementWrapper(name = "wrapperName")
No need to make a wrapper object. This will then be the route element in your marshalled XML response.
I used a custom iterable list using the following code, hope this helps.
package bindings;
import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlType
@XmlRootElement
public class CustomBindList<V> implements Iterable<V>, Serializable {
private static final long serialVersionUID = 4449835205581297830L;
@XmlElementWrapper(name = "List")
@XmlElement(name = "Entry")
private final List<V> list = new LinkedList<V>();
public CustomBindList() {
}
public void add(final V obj) {
list.add(obj);
}
public V get(final int index) {
return list.get(index);
}
@Override
public Iterator<V> iterator() {
return list.iterator();
}
public int size() {
return list.size();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With