如果提供的数据无法解组为预期的数据类型,是否可以将 JAXB 配置为引发异常?
我们有一个 Integer XmlElement,有时会得到像“1.1”这样的值作为输入 - Jaxb / Moxy 只是默默地忽略这些值并将它们设置为 null。我们通过使用对这些值进行四舍五入的 @XmlJavaTypeAdapter 解决了已知情况,但我们不知道是否有任何其他字段在错误数据上被默默忽略,并且希望有一个例外以获得清晰的反馈。
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Wrapper
{
@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
private Integer emptyNodeOnNull;
@XmlElement
private Integer ignoredOnNull;
}
以下测试应该抛出某种异常。
@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.");
}
我们现在对 JAXB 使用 Moxy 2.5.2,因为我们需要 @XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)。
您可以设置一个实例ValidationEventHandler
on the Unmarshaller
收集此类问题上的失败案例。
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)