1

Spring mvc配置Json返回

第一种

配置

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"  >
    <property name="ignoreDefaultModelOnRedirect" value="true" />
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        </list>
    </property>
</bean>

此方法不返回null属性,需要在对象类上声明

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Message implements Serializable {
    private String code;
    private String text;
    private Object data;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

 

第二种

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <!-- 处理responseBody 里面日期类型 -->
                    <property name="dateFormat">
                        <bean class="java.text.SimpleDateFormat">
                            <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
                        </bean>
                    </property>
                    <!-- 为null字段时不显示 -->
                    <property name="serializationInclusion">
                        <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
posted @ 2016-10-15 19:45  TinyKing  阅读(1841)  评论(0编辑  收藏  举报
我要啦免费统计