配置FastJson的消息转化器 —— FastJsonHttpMessageConverter注意事项
首先你得明白FastJsonHttpMessageConverter是干嘛的!
FastJsonHttpMessageConverter的作用
在SpringMVC中,需要进行JSON转换时,通常会使用FastJson提供的FastJsonHttpMessageConverter来完成,它的好处就是你不必将对象转化成JSON字符串,直接把获取的对象返回即可。
当你配置完FastJsonHttpMessageConverter
<!--配置FastJson的消息转化器 —— FastJsonHttpMessageConverter -->
<mvc:annotation-driven>
<mvc:message-converters>
<!--处理中文乱码-->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!--处理中文乱码-->
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
</list>
</property>
<property name="features">
<list>
<!-- Date的日期转换器 -->
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
若你想直接返回JSON数据,你需要controller层中直接把获取的对象返回即可
@RequestMapping(value="/view.json",method=RequestMethod.GET)
@ResponseBody
public User view(@RequestParam String id){
logger.debug("view id===================== "+id);
User user = new User();
try {
user = userService.getUserById(id);
}catch (Exception e){
e.printStackTrace();
}
//设置日期格式
JSONObject.DEFFAULT_DATE_FORMAT="yyyy-MM-dd";
JSONObject.toJSONString(user, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteDateUseDateFormat);
return user;
而不是再将user对象转化为JSON
@RequestMapping(value="/view.json",method=RequestMethod.GET)
@ResponseBody
public Object view(@RequestParam String id){
logger.debug("view id===================== "+id);
String cjson = "";
if(null == id || "".equals(id)){
return "nodata";
}else{
try {
User user = userService.getUserById(id);
//设置日期格式
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
cjson = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteDateUseDateFormat);
logger.debug("cjson ================== > " + cjson);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "failed";
}
return cjson;
}
}
否则就会出项未知错误,我上个博客遇到的冲突也许就是这个问题慎用FastJson的消息转化器 —— FastJsonHttpMessageConverter