springmvc @ResponseBody and @RequestBody ignore null fields

Technical background

  Accepting parameters: sometimes the front-end and back-end need to transmit data in json format. By default, springmvc encapsulates a parser that parses json strings into java objects in the background. If the front-end value is a json string, the corresponding request processing The server only needs to define an object that matches the json format, and add the @RequestBody annotation before it, and spring will complete the conversion process by itself.

  In the return parameter part, you can use @ResponseBody to convert the returned object into json format data.

In the above two cases, two problems will occur by default. In the receiving part, if the object defined in the background does not pass a value to the foreground, an exception will be thrown, and the return If some field values ​​are empty, the field will still be serialized into a json string, which consumes traffic.

  The relevant configuration is given below directly

   <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">
         < mvc:message-converters>
         <ref bean="jsonMessageConverter"/>
         </mvc:message-converters>
    </mvc:annotation-driven>

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        < property name="
            <ref bean="jacksonObjectMapper" />
        </property>
        <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>
<bean id="jacksonObjectMapper" 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>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326286914&siteId=291194637