I need to display null value as empty element in jaxb. I am using moxy implementation of jaxb. I found this option
@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
Is there any similar extension that can be applied at Class level (for all elements defined in it)
I would strongly recommend representing
null
with either the absence of the node or with thexsi:nil="true"
attribute. This works best with schema validation (i.e.<age/>
or<age></age>
is not a valid element of typexsd:int
. However if you can't here is how you can accomplish your use case:STANDARD JAXB BEHAVIOUR
Using the standard APIs you can control whether null is represented as an absent node or with
xsi:nil="true"
with the@XmlElement
annotation (see: http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html).Below is the XML output if the values of both fields are null.
MOXy - OVERRIDING THIS BEHAVIOUR PER CLASS
MOXy does not provide an annotation to specify the null policy for all the properties on a class. However you can leverage a
DescriptorCustomizer
via the@XmlCustomizer
annotation and tweak the native MOXy mapping metadata to accomplish the same thing.DescriptorCustomizer (AddressCustomizer)
DomainModel (Address)
Output
MOXy - OVERRIDING THIS BEHAVIOUR FOR ALL CLASSES
If instead you want to override null handling for all of the mapped classes I would recommend using a
SessionEventListener
instead. If you prefer you could also use this approach to update the metadata for a single class.SessionEventListener (NullPolicySessionEventListener)
Demo Code
Output
A "bad practice" workaround if you have only String fields in the class is to override the setter for the element like this:
This wont work with other types like date or number! But sometimes String is enought.
@Blaise Doughan's answer seems much better in long term if you can deal with it. :)