I have encountered a few issues when I try to parse XML object from the JAX-RS WebService. Many tutorials out there uses simple object. Just like I did in the previous post. Using one single class. However, in reality, if the Java class represents a complex object, typical Java will implements interface(s) and involves in parent/child relationship. In this circumstance, it is difficult to put @XmlRootElement all over the classes.
There are three options that we can take.
1. @XmlJavaTypeAdapter : Apply the adapter to hide implementation. By using adapter, you can specify the object that will be marshaled/unmarsharled. See JAXB Guide. I tried myself, but it has a problem at marshaling and I didn’t have a chance to dive into this route. At least, it didn’t complain about the object is an interface.
2. Simplify the object : Use a transfer class to make the object simple. Unless you need to pass the whole object & its attributes, simply the structure to represent the data.
3. Assign @XmlRootElement in the hierarchy : Make the JAXB work all the object in the hierarchy. Still it may require a trick. In case, declared variable is an Interface type, if the Interface is not complex, use substitute variable. If complex, use #1 technique or declare @XmlRootElement tag in the implementation class.
In my opinion, #2 seems the best solution when you need to deal with a complex object. Multiple inheritances with interface and abstract classes. Class is structured in this way to be flexible and useful within the domain. However, it may not be suitable to the outside of the domain. WebService is the tool to communicate the data to the outside, so why not spending little more time to make the object simpler?