1. SpringMVC 集成fastjson
在SpringMVC中集成fastjson, 集成之后,注解 @ResponseBody 返回的对象就能够自动解析成 json数据返回。
fastjson 的效率要高于 jackson、gson
配置 springmvc.xml 文件
<!--注册映射器,适配器,扫描注解-->
<mvc:annotation-driven conversion-service="conversionService">
<mvc:message-converters register-defaults="true">
<!--配置fastJson -->
<bean 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>
- 添加注解 @ResponseBody
@RequestMapping(value = "/ajax")
public @ResponseBody
Customer ajax(Integer id, HttpServletResponse response) {
Customer customer = customerService.queryCustomerById(id);
response.setContentType("text/html;charset=utf-8");
return customer;
}
返回的数据格式:
{
"cust_address": "北京三里桥",
"cust_createtime": 1460104321000,
"cust_id": 16,
"cust_industry": "2",
"cust_level": "22",
"cust_linkman": "马化腾",
"cust_mobile": "13888888888",
"cust_name": "刘强东",
"cust_phone": "0108888887",
"cust_source": "6",
"cust_zipcode": "123456"
}
2. 配置 fastjson 后,返回字符串时会在外面强制添加双引号
例如:
- 如果返回的字符串为
哈哈
, 最终返回得到的数据是"哈哈"
- 返回的字符串中包含双引号,例如
{"name":"ethan"}
,则 fastjson处理后,最终返回的结果是"{\"name\":\"ethan\"}"
要想得到原始字符串,解决办法:
添加配置字符串转换器StringHttpMessageConverter
<!--注册映射器,适配器,扫描注解-->
<mvc:annotation-driven conversion-service="conversionService">
<mvc:message-converters register-defaults="true">
<!--配置返回字符串,编码设置为UTF-8-->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/html;charset=UTF-8" />
</bean>
<!--配置fastJson-->
...
</mvc:message-converters>
</mvc:annotation-driven>