修改默认对象转换成 json 的转换器为 FastJSON?
网有很多关于该部分的内容,但大部分都是教怎返回 json 字符串而不是通过配置实现返回 json 格式的对象。而在现实开发中,大部分都用 ajax 来请求后端,而得到对象的 json 数据,比如微信小程序和 angularjs 等。废话有的多,下面开始,在此仅作整合参考。
1. 肯定是引入所需要的 jar 包
我自己用的是阿里的 FastJson
,网上还有很多用 jackson
maven 依赖如下:
1 2 3 4 5 6
| !--fastjson--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.31</version> </dependency>
|
2. 在 springmvc 的配置文件 springmvc.xml 中添加如下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| <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> <property name="features"> <array value-type="com.alibaba.fastjson.serializer.SerializerFeature"> <value>DisableCircularReferenceDetect</value> <value>WriteMapNullValue</value>
<value>WriteNullStringAsEmpty</value> <value>WriteNullListAsEmpty</value> </array> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
|
至于其中更多 value 及其用法参考 fastJson 的 SerializerFeature 属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <mvc:annotation-driven conversion-service="conversionService"> <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> <property name="features"> <array value-type="com.alibaba.fastjson.serializer.SerializerFeature"> <value>WriteNullStringAsEmpty</value> <value>WriteNullListAsEmpty</value> <value>WriteMapNullValue</value> <value>QuoteFieldNames</value> </array> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> //转换器 <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <ref bean="dateConvert"/> </set> </property> </bean>
|
配置完成,只要在 controller 层需要返回 json 格式的对象的方法加上 @ResponseBody 注解即可

