I have a nillable field in a class that is being set by the unmarshaller:
@XmlElement(name = "value", nillable = true)
private BigDecimal valueVariable;
My problem is that I can't tell if the xml element has been omitted or set to nil:
A. element <value/>
is missing from the XML file, it is not required.
=> (valueVariable == null) is true
B. XML file contains <value xsi:nil="true"/>
=> (valueVariable == null) is true
How can I tell for a non-String variable if the value is xsi:nil
or the tag is missing?
UPDATE You can see 2 good solutions, I preferred one of them, but the other would also be fine!
JAXB (JSR-222) implementations can represent
null
as either an absent node or a nillable element based on thenillable
setting on@XmlElement
. When you need to support both, or differentiate between the two then you can leverageJAXBElement
.Java Model
Root
Fields/properties of type
JAXBElement
are mapped with the@XmlElementRef
annotation. This corresponds to@XmlElementDecl
annotations on a class annotated with@XmlRegistry
.ObjectFactory
Demo Code
input.xml
Demo
Below is some demo code you can run to show that everything works. Note how the
JAXBIntrospector
can be used to get the real value unwrapping theJAXBElement
if necessary.Output
UPDATE
If you wanted to maintain your existing get/set methods, then you could keep field access as I have in this answer and change your accessor methods to look like the following:
Additionally you could add an
isSet
method to see if the value had been set.This approach does not require that you have access to the
Unmarshaller
. To make sure that theObjectFactory
is picked up you can use the@XmlSeeAlso
annotation to reference it from one of your domain classes.