springMVC和json整合配置方法
一、配置方法一
1、导入第三方的jackson包,jackson-mapper-asl-1.9.13.jar和jackson-core-asl-1.9.13.jar
百度云链接:https://pan.baidu.com/s/1snsjyNF,密码:8yp2
2、spring配置文件添加如下配置:
<mvc:annotation-driven/> <!-- 消息转换器,添加对文字编码的全局处理,解决中文返回问号的毛病 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 --> </list> </property> </bean>
二、配置方法二
1、导入第三方的fastjson包, fastjson-1.1.37.jar
百度云链接:https://pan.baidu.com/s/1snsPwy5 ,密码:g47f
2、spring配置文件添加如下配置:
<mvc:annotation-driven>
<!-- 消息转换器,添加对文字编码的全局处理,解决中文返回问号的毛病 -->
<mvc:message-converters register-defaults="true">
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
三、配置方法三
1、需要导入 jackson-annotations-*.jar,jackson-core-.jar,jackson-databind-.jar
百度云链接:https://pan.baidu.com/s/1nxbw9JF,密码:4s57
2、spring配置文件添加如下配置:
<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>