SpringMVC在处理json一般是采用默认的 Mapping-Jackson2HttpMessageConvert,这样的话在配置文件中使用默认配置即可
<mvc:annotation-driven/>
但是在使用第三方的fastjson处理json数据的话,则需要另行配置HttpMessageConvert.即
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
...
...
</mvc:message-converters>
</mvc:annotation-driven>
设置成为不使用默认的消息转换器,在spring官方文档中有这样一段话:
The MappingJackson2JsonView uses the Jackson library’s ObjectMapper to render the response content as JSON
Spring MVC默认使用MappingJackson2JsonView转换器,所以必须加入Jackson这个库的第三方类文件,则使用fastjson的话需要使用新的转换器,即com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter,FastJsonHttpMessageConverter是fastjson实现HttpMessageConverter接口的类.
最终配置为
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
...
...
<bean id="fastJsonHttpMessageConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!-- 加入支持的媒体类型:返回contentType -->
<property name="supportedMediaTypes">
<list>
<!-- 这里顺序不能反,一定先写text/html,不然ie下会出现下载提示 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
如果加入了fastjson相关的jar包,但是没有配置转换器,则会在发送数据时出现
Handler execution resulted in exception:Content type ‘application/json;charset=utf-8’not supported 错误
版权声明:本文为qq_25652213原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。