1. 程式人生 > >spring mvc如何優雅的使用fastjson

spring mvc如何優雅的使用fastjson

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資料中有陣列就無能為力了:例如:

  解決辦法:

   @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