美文网首页
spring mvc 使用 json 遇到的问题:大小写和过滤n

spring mvc 使用 json 遇到的问题:大小写和过滤n

作者: s丶heart | 来源:发表于2017-05-13 17:25 被阅读1848次

使用Jackson

  1. 返回的 json 没有 null 字段 , 即返回的 bean 中没有值的字段不返回 .
<!-- json支持 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="cacheSeconds" value="0" />
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper">

                        <!-- 为null字段时不显示 -->
                        <property name="serializationInclusion">
                            <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
                        </property>
                    </bean>
                </property>

            </bean>

        </list>
    </property>
</bean>
  1. 字段 CREATE_DATE 会自动转换成小写 : "create_DATE":"2017-04-25 13:23:56.0"
    解决办法:加入注解
@JsonProperty("CREATE_DATE")
private String CREATE_DATE;

但是不知道为什么会出现两个字段 : "create_DATE":"2017-04-25 13:23:56.0","CREATE_DATE":"2017-04-25 13:23:56.0"


使用fastjson

  1. 返回的 json 没有 null 字段,fastjson 会自动过滤 null 字段。
<!-- json支持 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="cacheSeconds" value="0" />
    <property name="messageConverters">
        <list>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </list>
    </property>
</bean>
  1. 这时候出现字段大小写问题,bean 中的字段为:
private String CREATE_DATE;

返回的 json 为 "cREATE_DATE":"2017-04-25 13:23:56.0" 。
解决办法:加注解

@JSONField( name="CREATE_DATE")
private String CREATE_DATE;

通过解决上面的两个问题发现,fastjson 比较好点。

相关文章

网友评论

      本文标题:spring mvc 使用 json 遇到的问题:大小写和过滤n

      本文链接:https://www.haomeiwen.com/subject/pmgxxxtx.html