We will often need to unmarshal Java objects that do not have JAXB annotations, and we are not permitted to make any changes in the source code. This situation may occur when we are working with legacy code or some client jar for which we do not have source code.
1. Problem when unmarshaling without JAXB annotations
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"employee").Expected elements are (none)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:726)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:247)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:242)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:109)
Where Employee.java class is as below. It does not have any JAXB annotation such as @XmlRootElement.
publicclassEmployeeimplementsSerializable{privatestaticfinallong serialVersionUID =1L;privateInteger id;privateString firstName;privateString lastName;privateDepartment department;//constructors, getters and setters@OverridepublicStringtoString(){return"Employee [id="+ id +", firstName="+ firstName +", lastName="+ lastName +", department="+ department +"]";}}
2. Solution to Unmarshal without JAXB annotations
In absence of @XmlRootElement annotation, JAXB is not able to build JAXBElement instance for Employee object. So that’s where you have to help JAXB to construct it manually.
/**
* Unmarshal XML data from the specified XML Source by <tt>declaredType</tt> and return the
* resulting content tree.
* @param source source the XML Source to unmarshal XML data from (providers are
* only required to support SAXSource, DOMSource, and StreamSource)
*
* @param declaredType appropriate JAXB mapped class to hold <tt>source</tt>'s xml root element
*
* @return value Java content rooted by JAXB Element
*/public<T>JAXBElement<T>unmarshal(javax.xml.transform.Source source,Class<T> declaredType )throwsJAXBException;
A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Comments