如何配置JAXB / Moxy以在XML中丢失潜在的丢失数据错误 [英] How to configure JAXB / Moxy to throw an error on potential lost data in XML

查看:121
本文介绍了如何配置JAXB / Moxy以在XML中丢失潜在的丢失数据错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果提供的数据不能解组到预期的数据类型中,是否可以将JAXB配置为抛出异常?

Is it possible to configure JAXB to throw an exception if the supplied data is not unmarshalable into the expected data type?

我们有一个Integer XmlElement,有时会得到值比如1.1作为输入 - Jaxb / Moxy只是默默地忽略这些值并将它们设置为null。我们通过使用舍入这些值的@XmlJavaTypeAdapter解决了已知情况,但是我们不知道是否有任何其他字段在错误数据上被忽略,并且更喜欢异常以获得清晰的反馈。

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.");
}

我们现在使用Moxy 2.5.2 for JAXB,因为我们需要@ XmlNullPolicy(emptyNodeRepresentsNull = true,nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)。

We use Moxy 2.5.2 for JAXB right now, as we need the @XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE).

推荐答案

您可以设置的实例在此类问题上收集失败的 Unmarshaller 上的ValidationEventHandler

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;
}

}

这篇关于如何配置JAXB / Moxy以在XML中丢失潜在的丢失数据错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆