I am trying to unmarshall Xml returned from a rest call into POJOs. However, one call can return different types of documents with different root elements e.g.
<obj1> ... </obj1>
<obj2> ... </obj2>
I unmarshal using a generic function:
private <T> T unmarshal(String xml, Class<T> clazz) {
JAXBContext jc = JAXBContext.newInstance(clazz);
return clazz.cast(jc.createUnmarshaller().unmarshal(new StringReader(xml));
}
I've created to separate classes for each of the different roots, but I don't know how I can check the root element type and then call my unmarshall function with the correct type?
if rootElement.equals("obj1")
Obj1 obj = unmarshal(xml, Obj1.class)
else if rootElement.equals("obj2")
Obj2 obj = unmarshal(xml, Obj2.class)
Is there a way using JaxB to do this conditional checking on a root element?