最近研究EROS两端统一(WEB+Android),发现WEB端axios和bmAxios的处理方式不一致。这个将导致迁移后所有的null逻辑和undefined逻辑互换,为了避免这个业务问题,必须都统一起来。
由于bmAxios包括WEEX底层都是使用fastjson做的JSON序列化,而fastjson默认的JSONObject又是忽略null属性的,导致和WEB的axios处理不一致。权衡了修改难度,决定从服务器端入手,将WEB和Andoid端统一起来。
服务器是spring mvc 5.X的,按照网上简单的修改serializationInclusion为NULL后,出现400错误,而去掉serializationInclusion却可以正常请求。
经过仔细研究,发现导致400的问题是因为传递了额外的参数(VUE使用了一个合并多个模型的对象)。尝试关闭failOnUnknownProperties后就能正常工作。因此必须采用以下方式,才能开启忽略null属性并保持和spring默认的json工作一致(忽略额外属性):
<mvc:annotation-driven><!-- 只能有一个annotation-driven -->
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnUnknownProperties" value="false"/><!-- 忽略object以外的属性 -->
<property name="serializationInclusion"><value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value></property><!-- null值不输出,和APP端fastjson呈现一致 -->
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
核心的方案是采用Jackson2ObjectMapperFactoryBean去配置objectMapper,该FactoryBean支持了failOnUnknownProperties的配置。