Search code examples
jsonmuleanypoint-studiojackson2jackson-databind

How to exclude null values while converting object to json


I am working with MuleSoft Anypoint Studio and I need to convert JSON payload to in the end XML. During this conversion every field that is NULL need to be excluded. Some values are not sent via POST request and I am expecting to not see them in the end result - XML file but that is not the case as they are there. For example in the JSON POST request Value field is not sent, which becomes null in Mule so it should not appear in the XML file but it's still written in it as <Value/>. I am mainly having problems with Object to JSON transformer.

I have tried configuring a custom mapper

 <spring:beans>
     <spring:bean id="Bean" name="NonNullMapper" class="org.codehaus.jackson.map.ObjectMapper">
         <spring:property name="SerializationInclusion">
            <spring:value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</spring:value>
         </spring:property>
     </spring:bean>

But that didn't really work. I also tried

<spring:beans>
     <spring:bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
     <spring:bean
         class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
         <spring:property name="targetObject" ref="jacksonObjectMapper" />
         <spring:property name="targetMethod" value="configure" />
         <spring:property name="arguments">
             <spring:list>
                 <spring:value>WRITE_NULL_MAP_VALUES</spring:value>
                 <spring:value>false</spring:value>
             </spring:list>
         </spring:property>
     </spring:bean>
 </spring:beans>

That didn't work too as I get an error which I couldn't manage to fix

More than one object of type class org.codehaus.jackson.map.ObjectMapper registered but only one expected

I am working with

  • Mule 3.9.0
  • Anypoint Studio 6.4
  • com.fasterxml.jackson and in some places org.codehaus.jackson

I would really appreciate any help or some hint.


Solution

  • Given that this in Mule, you can use DataWeave instead to transform the payload. Setting the XML writer property skipNullOn could give the desired result. https://docs.mulesoft.com/mule-user-guide/v/3.9/dataweave-formats#skip-null-on

    Example

    %output application/xml skipNullOn="payload"
    ---
    payload