Jackson FasterXML不会因无效XML而失败

时间:2019-09-10 13:12:38

标签: java xml jackson-databind jackson-dataformat-xml

下面的代码不会引发错误,也许无法解析,但是会以appConfig的形式返回null字段。我尝试过JAXB,与JAXB抛出错误不同。我需要在xml无效时无法解析我的代码。我该怎么办?

Pojo:

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

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

XML(config-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(config-invalid.xml):

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

1 个答案:

答案 0 :(得分:1)

添加以下行,否则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);
........