Spring REST Service: how to configure to remove null objects in json response

前端 未结 10 1148
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 07:06

I have a spring webservice that returns a json response. I\'m using the example given here to create the service: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-exam

相关标签:
10条回答
  • 2020-11-28 07:59

    Since Jackson 2.0 you can use JsonInclude

    @JsonInclude(Include.NON_NULL)
    public class Shop {
        //...
    }
    
    0 讨论(0)
  • 2020-11-28 08:01
    @JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
    public class Shop {
        //...
    }
    

    for jackson 2.0 or later use @JsonInclude(Include.NON_NULL)

    This will remove both empty and null Objects.

    0 讨论(0)
  • 2020-11-28 08:05

    You can use JsonWriteNullProperties for older versions of Jackson.

    For Jackson 1.9+, use JsonSerialize.include.

    0 讨论(0)
  • 2020-11-28 08:06

    I've found a solution through configuring the Spring container, but it's still not exactly what I wanted.

    I rolled back to Spring 3.0.5, removed and in it's place I changed my config file to:

        <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean
                    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                    <property name="objectMapper" ref="jacksonObjectMapper" />
                </bean>
            </list>
        </property>
    </bean>
    
    
    <bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
    <bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
        factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
    <bean
        class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="jacksonSerializationConfig" />
        <property name="targetMethod" value="setSerializationInclusion" />
        <property name="arguments">
            <list>
                <value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
            </list>
        </property>
    </bean>
    

    This is of course similar to responses given in other questions e.g.

    configuring the jacksonObjectMapper not working in spring mvc 3

    The important thing to note is that mvc:annotation-driven and AnnotationMethodHandlerAdapter cannot be used in the same context.

    I'm still unable to get it working with Spring 3.1 and mvc:annotation-driven though. A solution that uses mvc:annotation-driven and all the benefits that accompany it would be far better I think. If anyone could show me how to do this, that would be great.

    0 讨论(0)
提交回复
热议问题