javaapache-cameljackson-dataformat-xmlcamel-jackson

Enable EMPTY_ELEMENT_AS_NULL in Camel 3 XML DSL


I've found here that the default behaviour for FromXmlParser.Feature.EMPTY_ELEMENT_AS_NULL has changed from true (2.9 - 2.11) to false (2.12 onwards), so from that version no automatic coercion is done from empty elements like into null.

I was using Apache Camel 2.25 and that version had this feature enabled by default but now, with this change, is disabled in Camel 3.x. How can I enable it in back in Camel 3 using XML DSL? I know using XMLMapper is easy enough:

XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(FromXmlParser.Feature.EMPTY_ELEMENT_AS_NULL, true);

But in Camel XML DSL the allowed enums are only the ones from SerializationFeature, DeserializationFeature and MapperFeature. I've tried with some of them but with no luck.

<unmarshal>
   <jacksonxml disableFeatures="FAIL_ON_UNKNOWN_PROPERTIES"
      enableFeatures="ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT"
      unmarshalTypeName="com.my.class.Result" 
      include="NON_NULL" />
</unmarshal>

Solution

  • You can set a custom xmlMapper on the jacksonxml element, the attribute is called "xmlMapper" you can then reference your custom XmlMapper which should be declared as a bean, but this is important, you must include a # before the bean name or else the object mapper will not be looked up and will be set to null and a default one will be created.

      @Bean
      public XmlMapper customXMLMapper(){
        return XmlMapper.builder()
                .configure(EMPTY_ELEMENT_AS_NULL, true)
                .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
                .build();
      }
    
    <unmarshal>
        <jacksonxml unmarshalTypeName="com.myclass.Result" xmlMapper="#customXMLMapper"/>
    </unmarshal>