Reputation: 729
Am using an implementation of MessageBodyWriter
to marshall all my objects to a file(XML).
@XmlRootElement(name="root")
@XmlAccessorType( XmlAccessType.FIELD )
class Myclass implements MyInterface{
// some private fields
}
interface MyInterface{
//some methods
}
I have a List<MyClass>
objects to save in XML,
But when i call Marshaller.marshall(object, outputstream)
i got this exception :
[com.sun.istack.SAXException2: unable to marshall type "..MyClass" as an element because it is missing @XmlRootElement annotation]
But the thing is that I do have that annotation on MyClass
.
Any idea on what is wrong on my marshalling process?
Thanks
Upvotes: 1
Views: 1267
Reputation: 5062
You can marshall a single instance, right?
MyClass myClass1 = new MyClass();
myClass1.setField("value");
JAXB.marshal(myClass1, writer);
But I assume you try to marshall a list? Something like
List<MyClass> list = new ArrayList<MyClass>();
list.add(myClass1);
JAXBContext.newInstance(ArrayList.class).createMarshaller().marshal(list, writer);
If you want to marshall a list in one XML document you need a wrapper class:
@XmlRootElement(name="root")
@XmlAccessorType( XmlAccessType.FIELD )
public class MyWrapper {
@XmlElement(name="child")
private List<MyClass> list = new ArrayList<MyClass>();
public List<MyClass> getList() {
return list;
}
...
Then it should work, e.g.:
MyClass myClass1 = new MyClass();
myClass1.setField("value");
MyWrapper wrapper = new MyWrapper();
wrapper.getList().add(myClass1);
JAXB.marshal(wrapper, writer);
results in
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<child>
<field>value</field>
</child>
</root>
Upvotes: 2