I am trying to implement a XmlAdapter for modifying the marshalling/unmarshalling of certain object properties. Particularly, I tried with the NullStringAdapter described here:
Jaxb: xs:attribute null values
The objective of the NullStringAdapter is marshalling null values as empty strings, and viceversa.
The only difference with the example described above and my code, is that I want to apply the adapter to an element, not to an attribute, so what I have is:
@XmlElement
@XmlJavaTypeAdapter(NullStringAdapter.class)
public String getSomeValue() {
return someValue; //someValue could be null, in that case the adapter should marshall it as an empty string
}
However, after some debugging, I realized that the Adapter methods are never called during the marshalling from Java to XML!. This occurs when the XmlElement value is null.
When this value is different than null, the adapter methods are called as expected.
Thanks for any help!.
Note: I’m the EclipseLink JAXB (MOXy) lead, and a member of the JAXB 2 (JSR-222) expert group.
This behaviour varies between implementations of JAXB. The JAXB reference implementation will not call the marshal method on the
XmlAdapterwhen the field/property is null, but MOXy will.What the JAXB spec says (section 5.5.1 Simple Property)
The MOXy interpretation of this statement is that the value of the field/property is really the value once it has gone through the
XmlAdapter. This is necessary to support the behaviour that Sergio is looking for.