Tag Archives: json

Remove null values from JSON object and ignore unavailable properties

The definition of web services using Spring is quite easy (see here for details), based on Jackson, the data marshalling/unmarshalling is totally hidden to the developer and it works perfectly.
But I encountered performance issues with the null values, I had to manage some classes with a lot of data, and they often contain empty values, resulting in a Json which was mainly composed of empty attributes (a lot) and it takes time to transfer it on the wire. To reduce the amount of data to transfer and then improve the response performance, it is possible to ask Jackson to include only non null values:

<bean id="jacksonObjectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
	<property name="serializationInclusion">
		<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
	</property>
</bean>

Another problem raised when I tried to pass json content with attribute which were not defined in my Java classes. The most obvious option is to change the implementation to add this new parameter, but I preferred to keep it unchanged and decided to manage it globally.
That’s how I did it:

<bean
	class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
	<property name="targetObject" ref="jacksonObjectMapper" />
	<property name="targetMethod" value="configure" />
	<property name="arguments">
		<list>
			<value type="com.fasterxml.jackson.databind.DeserializationFeature">FAIL_ON_UNKNOWN_PROPERTIES</value>
			<value>false</value>
		</list>
	</property>
</bean>
<mvc:annotation-driven >
	<mvc:message-converters register-defaults="true">
		<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
			<property name="objectMapper" ref="jacksonObjectMapper"/>
		</bean>
	</mvc:message-converters>
	
</mvc:annotation-driven>