How to configure JAXB / Moxy to throw an error on potential lost data in XML

陌路散爱 提交于 2019-12-10 10:52:23

问题


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).


回答1:


You can set an instance of ValidationEventHandler on the Unmarshaller to collect of fail on this type of issue.

public class DeserializationEventHandler implements ValidationEventHandler
{
private static final Logger LOG = LoggerFactory.getLogger(DeserializationEventHandler.class);

@Override
public boolean handleEvent(ValidationEvent event)
{
    LOG.warn("Error during XML conversion: {}", event);

    if (event.getLinkedException() instanceof NumberFormatException)
        return false;

    return true;
}

}



来源:https://stackoverflow.com/questions/26972237/how-to-configure-jaxb-moxy-to-throw-an-error-on-potential-lost-data-in-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!