Is it possible to configure JAXB to throw an exception if the supplied data is not unmarshalable into the expected data type?
We have a Integer XmlElement and sometimes get values like "1.1" as input - Jaxb / Moxy just silently ignores these values and sets them to null. We solved it for the known cases by using a @XmlJavaTypeAdapter that rounds those values, but we won't know if any other fields get silently ignored on wrong data and would prefer a exception for clear feedback.
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Wrapper
{
@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
private Integer emptyNodeOnNull;
@XmlElement
private Integer ignoredOnNull;
}
The following test should throw some kind of exception..
@Test(expected = IllegalArgumentException.class)
public void testUnmarshallWithInvalidValue() throws Exception
{
JAXBContext context = JAXBContext.newInstance(Wrapper.class);
StreamSource source = new StreamSource(
new StringReader(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><wrapper><emptyNodeOnNull>1.1</emptyNodeOnNull><ignoredOnNull>2.2</ignoredOnNull></wrapper>"));
context.createUnmarshaller().unmarshal(source, Wrapper.class);
fail("Should have thrown some kind of exception due to lost data.");
}
We use Moxy 2.5.2 for JAXB right now, as we need the @XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE).
You can set an instance of
ValidationEventHandler
on theUnmarshaller
to collect of fail on this type of issue.}