The problem is in the following :
I get the soap response with empty element inside (e.g. ... <someDate /> ...
)
and as a result exception is being throwed when JAXB wants to parse this element
instead to set the appropriate field with null
value.
How to configure JAXB to treat empty elements as null ? Can we do this with JAXB only (not using some third-party workarounds)
Base Problem
Empty
String
is not a valid value for thexsd:date
type. To be valid with the XML schema an optional element should be represented as an absent node.,Why the Base Problem is Impacting You
All JAXB implementations will recognize that empty
String
is not a valid value forxsd:date
. They do this by reporting it to an instance ofValidationEventHandler
. You can see this yourself by doing the following:The implementation of JAX-WS you are using, leverages EclipseLink MOXy as the JAXB provider. And in the version you are using MOXy will by default throw an exception when a
ValidationEvent
of severityERROR
is encountered instead ofFATAL_ERROR
like the reference implementation. This has since been fixed in the following bug:Work Around
If you are using the JAXB APIs directly you could simply override the default
ValidationEventHandler
. In a JAX-WS environment aXmlAdapter
can be used to provide custom conversion logic. We will leverage anXmlAdapter
to override how the conversion to/fromDate
is handled.XmlAdapter (DateAdapter)
Java Model (Root)
The
XmlAdapter
is referenced using the@XmlJavaTypeAdapter
annotation. If you wish thisXmlAdapter
to apply to all instances ofDate
you can register it at the package level (see: http://blog.bdoughan.com/2012/02/jaxb-and-package-level-xmladapters.html).Demo Code
Below is a standalone example you can run to see that everything works.
jaxb.properties
In a standalone example to use MOXy as your JAXB provider you need to include a file called
jaxb.propeties
in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).input.xml
Demo
Output
Note that in the marshalled XML the
Date
field that was null was marshalled as an absent element (see: http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html).