I have a situation here, trying to act as a gateway between two APIs. What I need to do, is:
- make a request to an APIa;
- parse (marshal) the XML response into an java object;
- make little changes to it;
- and then give a response in XML (unmarshal) to the other end (APIb).
The thing is that I use the same object to parse the API response and to send the response to the other end.
public class ResponseAPI{
@XmlElement(name="ResponseCode") //I receive <ResponseCode> but I need to send <ResultCode>
private String responseCode;
//getter and setter
}
as the comment says: I receive but I need to send
Is there a way to get this done without having to create another extra class which carries ResultCode?
thanks in advance!
Note:
The answer given by Ilya works but isn't guaranteed to work across all implementations of JAXB or even across versions of a single JAXB implementation. The
@XmlElements
annotation is useful when the decision of which element to marshal depends on the type of the value (see: http://blog.bdoughan.com/2010/10/jaxb-and-xsd-choice-xmlelements.html). In your use case both theResponseCode
andResultCode
elements correspond to typeString
, unmarshalling will always work fine, but the choice of which element to output is arbitrary. Some JAXB Impls may have last specified wins, but others could easily have first wins.You could do the following by leveraging
@XmlElementRef
.Java Model
ResponseAPI
We will change the
responseCode
property from typeString
toJAXBElement<String>
. TheJAXBElement
allows us to store the element name as well as the value.ObjectFactory
The
@XmlElementRef
annotations we used on theResponseAPI
class correspond to@XmlElementDecl
annotations on a class annotated with@XmlRegistry
. Traditionally this class is calledObjectFactory
but you can call it anything you want.Demo Code
input.xml
Demo
When creating the
JAXBContext
we need to ensure that we include the class that contains the@XmlElementDecl
annotations.Output
You can try next solution using @XmlElements annotaion
In this case both
ResponseCode
andResultCode
will be used during unmarshalling (xml -> object) and onlyResultCode
during marshalling (object -> xml).So you can unmarshall XML like
After marshalling object will looks like