网有很多关于该部分的内容,但大部分都是教怎返回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注解即可

