Search code examples
javaxmljackson-databindjackson-dataformat-xml

Jackson FasterXML doesn't fail for invalid XML


Below code doesn't throw error, maybe it couldn't parse, but returns appConfig fields as null. I've tried JAXB, unlike that JAXB throws error. I need that my code couldn't parse when xml is invalid. How can I do that?

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>

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



It throws only xml like below: XML(config-invalid.xml):

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

Solution

  • Add the below line otherwise Jackson XML ignores the root element.

    xmlMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
    

    I provide below the code snippet, you can check.

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