1. 在spring mvc中配置fastjson

<!-- 设置配置方案 -->
<mvc:annotation-driven>
<!-- 设置不使用默认的消息转换器 -->
<mvc:message-converters register-defaults="false">
<!-- 配置Spring的转换器, 字符编码 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" index="0"/>
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<!--配置fastjson中实现HttpMessageConverter接口的转换器-->
<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>
<!--枚举类型,对于返回List集合中引用同一个对象,忽略引用检测【注意不要出现循环引用现象】-->
<property name="features">
<list>
<value>DisableCircularReferenceDetect</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

2. 使用方法

    // 文章details
@RequestMapping(value = "/detail", method = RequestMethod.GET)
public String detail(Long id, Model model, HttpServletRequest request){
Article article = articleService.getArticleById(id, request); Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
if(teacher==null){
return "login.jsp";
}
// role : 1-teacher
ArticleZan zan = articleService.getZan(article.getArticle_id(), 1, teacher.getTe_id());
model.addAttribute("article", article);
model.addAttribute("zan",zan);
return "article/detail.jsp";
}

  {"id":1}  ->可以完成参数疯转

  

  对于普通的参数,fastjson可以完成参数封装和类型转换。但是对于JSON数据中有数组就无能为力了:例如:

spring mvc如何优雅的使用fastjson-LMLPHP

  解决办法:

   @CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(value = "/getArticles")
@ResponseBody
public Object getArticles(Long[] id, @RequestBody JSONObject[] obj, HttpServletRequest request){
Set<Long> ids = new HashSet<>();
for (JSONObject o :
obj) {
ids.add(o.getLong("id"));
}
List<Article> articles = articleService.getArticles(ids, request);
return articles;
}

end

05-14 07:41