Jackson FasterXML 不会因无效 XML 而失败

Jackson FasterXML doesn't fail for invalid XML

下面的代码没有抛出错误,也许它无法解析,但是 returns appConfig 字段为 null。我试过 JAXB,不像 JAXB 抛出错误。当 xml 无效时,我需要我的代码无法解析。我该怎么做?

波乔:

import lombok.Data;
import com.fasterxml.jackson.annotation.JsonRootName;

@Data
@JsonRootName("app-config")
public class Config {
    private String type;
    private String body;
}

XML(配置-invalid.xml):

<?xml version="1.0" encoding="UTF-8"?>
<invalid></invalid>

反序列化XML:

...
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
xmlMapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Config appConfig = xmlMapper.readValue(new File("config-invalid.xml"), Config.class);
...



它只抛出 xml 如下所示: XML(配置-invalid.xml):

<?xml version="1.0" encoding="UTF-8"?>
<app-config>
    <invalid></invalid>
</app-config>

添加以下行,否则 Jackson XML 将忽略根元素。

xmlMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);

我在下面提供了代码片段,你可以查看。

........
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
xmlMapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
xmlMapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
........