骡子对象到json变换器:如何排除空值?

时间:2016-05-24 04:03:16

标签: mule

有没有办法指示Mule对象到json-transformer组件不在生成的JSON中包含null属性?

默认情况下,它会为null对象属性生成类似的内容:

"value": null

谢谢,

PS。只是想澄清我正在寻找一种在Mule中配置它的方法,而不是使用类jackson注释。

3 个答案:

答案 0 :(得分:3)

好的,我找到了答案。

Mule object-to-json变换器忽略了jackson注释。

相反,您需要定义一个自定义的对象映射器bean,如下所示:

<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>
</spring:beans>

然后像这样引用变换器中的bean:

<json:object-to-json-transformer doc:name="Object to JSON" mapper-ref="NonNullMapper"/>

请注意,此方法仅适用于自定义java类。

答案 1 :(得分:1)

使用此@JsonSerialize (include = JsonSerialize.Inclusion.NON_NULL),只需将其放在其类中即可。要导入的库是导入org.codehaus.jackson.map.annotate.JsonSerialize

答案 2 :(得分:0)

您可以配置json变换器使用的ObjectMapper,如下所示:

<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_VALUES</spring:value>
                    <spring:value>false</spring:value>
                </spring:list>
            </spring:property>
        </spring:bean>
    </spring:beans>

    <flow name="json" >

        ...
        <json:object-to-json-transformer mapper-ref="jacksonObjectMapper" />

    </flow>

或者如果您使用地图:

<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>

    <flow name="json" >

        ...
        <json:object-to-json-transformer mapper-ref="jacksonObjectMapper" />

    </flow>