SpringMVC集成fastjson遇到的問題

1. SpringMVC 集成fastjson

在SpringMVC中集成fastjson, 集成之后,注解 @ResponseBody 返回的對象就能夠自動解析成 json數(shù)據(jù)返回。
fastjson 的效率要高于 jackson、gson

  1. 下載 fastjson.jar

  2. 配置 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>
  1. 添加注解 @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;
    }

返回的數(shù)據(jù)格式:


{
    "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 后,返回字符串時會在外面強制添加雙引號

例如:

  1. 如果返回的字符串為 哈哈, 最終返回得到的數(shù)據(jù)是 "哈哈"
  2. 返回的字符串中包含雙引號,例如{"name":"ethan"},則 fastjson處理后,最終返回的結(jié)果是 "{\"name\":\"ethan\"}"

要想得到原始字符串,解決辦法:
添加配置字符串轉(zhuǎn)換器StringHttpMessageConverter

    <!--注冊映射器,適配器,掃描注解-->
    <mvc:annotation-driven conversion-service="conversionService">
        <mvc:message-converters register-defaults="true">
            <!--配置返回字符串,編碼設(shè)置為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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,568評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,273評論 6 342
  • 1. 簡介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優(yōu)秀的...
    笨鳥慢飛閱讀 6,241評論 0 4
  • 這兩天,在項目導(dǎo)入一個SDK,在本地調(diào)試沒有任何問題,然后上傳至svn服務(wù)器后,再checkout下來就發(fā)現(xiàn)少了好...
    娶什么名字呢閱讀 447評論 0 0
  • 當(dāng)提起筆寫下這個題目的時候,突然覺得自己好可笑 愛情被人類一直認(rèn)為是至上的感情 出軌被人類一直認(rèn)為是可恥的行為 出...
    愛芯妍902閱讀 288評論 0 0

友情鏈接更多精彩內(nèi)容