SpringMVC使用第三方fastjson配置

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 錯誤

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章