SpringMVC集成fastjson遇到的问题

1. SpringMVC 集成fastjson

在SpringMVC中集成fastjson, 集成之后,注解 @ResponseBody 返回的对象就能够自动解析成 json数据返回。
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;
    }

返回的数据格式:


{
    "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. 如果返回的字符串为 哈哈, 最终返回得到的数据是 "哈哈"
  2. 返回的字符串中包含双引号,例如{"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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,224评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,204评论 6 342
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 11,228评论 0 4
  • 这两天,在项目导入一个SDK,在本地调试没有任何问题,然后上传至svn服务器后,再checkout下来就发现少了好...
    娶什么名字呢阅读 3,093评论 0 0
  • 当提起笔写下这个题目的时候,突然觉得自己好可笑 爱情被人类一直认为是至上的感情 出轨被人类一直认为是可耻的行为 出...
    爱芯妍902阅读 1,751评论 0 0

友情链接更多精彩内容