30

a sample of json response looks like this:

{"publicId":"123","status":null,"partner":null,"description":null}

It would be nice to truncate out all null objects in the response. In this case, the response would become {"publicId":"123"}.

Any advice? Thanks!

P.S: I think I can do that in Jersey. Also I believe they both use Jackson as the JSON processer.

Added Later: My configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.SomeCompany.web" />

    <!-- Application Message Bundle -->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages/messages" />
        <property name="cacheSeconds" value="0" />
    </bean>

    <!-- Configures Spring MVC -->
    <import resource="mvc-config.xml" />

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <!-- Forwards requests to the "/" resource to the "welcome" view -->
    <!--<mvc:view-controller path="/" view-name="welcome"/>-->

    <!-- Configures Handler Interceptors -->    
    <mvc:interceptors>
        <!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
    </mvc:interceptors>

    <!-- Saves a locale change using a cookie -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />

    <!--<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                <entry key="atom" value="application/atom+xml"/>
                <entry key="html" value="text/html"/>
                <entry key="json" value="application/json"/>
                <entry key="xml" value="text/xml"/>
            </map>
        </property>
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/views/"/>
                    <property name="suffix" value=".jsp"/>
                </bean>
            </list>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView" >
                    <property name="marshaller">
                        <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller" />
                    </property>
                </bean>
            </list>
        </property>
    </bean>
-->
  <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

My code:

@Controller
public class SomeController {
    @RequestMapping(value = "/xyz", method = {RequestMethod.GET, RequestMethod.HEAD},
    headers = {"x-requested-with=XMLHttpRequest","Accept=application/json"}, params = "!closed")
    public @ResponseBody
    List<AbcTO> getStuff(
          .......
    }
}
Bobo
  • 8,777
  • 18
  • 66
  • 85
  • How are you using Jackson? What do your controllers and config look like? – skaffman May 18 '11 at 18:46
  • 1
    I am not using Jackson directly. How Jackson is used is spring-mvc's internal implementation. Basically this JSON thing is given for free in spring-mvc 3. – Bobo May 18 '11 at 19:10
  • Yes, I know that. I asked to see your controllers and config because that determines how Spring uses Jackson. – skaffman May 18 '11 at 19:15
  • http://stackoverflow.com/questions/12707165/spring-rest-service-how-to-configure-to-remove-null-objects-in-json-response – Francisco M Apr 28 '17 at 12:47

4 Answers4

32

Yes, you can do this for individual classes by annotating them with @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) or you can do it across the board by configuring your ObjectMapper, setting the serialization inclusion to JsonSerialize.Inclusion.NON_NULL.

Here is some info from the Jackson FAQ: http://wiki.fasterxml.com/JacksonAnnotationSerializeNulls.

Annotating the classes is straightforward, but configuring the ObjectMapper serialization config slightly trickier. There is some specific info on doing the latter here.

Community
  • 1
  • 1
BennyFlint
  • 610
  • 6
  • 10
  • tried the approach of "configuring the ObjectMapper serialization" based on this http://stackoverflow.com/questions/4823358/spring-configure-responsebody-json-format. Did not work, caused by "Rejected bean name 'jacksonObjectMapper': no URL paths identified". – Bobo May 19 '11 at 13:55
  • 1
    the include attribute is deprecated – Alex R Dec 08 '15 at 02:34
  • the above attribute is deprecated – Chetan Dec 15 '15 at 10:58
20

Doesn't answer the question but this is the second google result.

If anybody comes here and wants do do it for Spring 4 (as it happened to me), you can use the annotation

@JsonInclude(Include.NON_NULL)

on the returning class.

As mentioned in the comments, and in case anyone is confused, the annotation should be used in the class that will be converted to JSON.

Mário Fernandes
  • 1,822
  • 1
  • 21
  • 21
9

If using Spring Boot for REST, you can do it in application.properties:

spring.jackson.serialization-inclusion=NON_NULL

source

Luís Soares
  • 5,726
  • 4
  • 39
  • 66
  • Unfortunately this works only for Spring Boot 1.3. http://docs.spring.io/spring-boot/docs/1.2.8.RELEASE/reference/htmlsingle/#howto-customize-the-jackson-objectmapper does not contain this line. – Johannes Flügel May 11 '16 at 07:51
  • 4
    I use `spring.jackson.default-property-inclusion=non_absent`, with spring boot 1.5.3 – Doug Hou Apr 26 '17 at 07:52
1

Java configuration for the above. Just place the below in your @Configuration class.

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.serializationInclusion(JsonInclude.Include.NON_NULL);
    return builder;
}
Norbert
  • 809
  • 9
  • 13