Spring MVC使用fastjson做消息转换器,与默认Jackson的区别

来源:互联网 发布:念诗 知乎 编辑:程序博客网 时间:2024/06/06 01:10

spring mvc支持自定义HttpMessageConverter接收JSON格式的数据,使用fastjson作为消息装换器,只需要在spring的配置文件中加入如下配置代码(需引入fastjson依赖包):

<mvc:annotation-driven>    <!--设置不使用默认的消息转换器-->    <mvc:message-converters register-defaults="false">        <!--配置spring的转换器-->        <bean class="org.springframework.http.converter.StringHttpMessageConverter" />        <bean class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter" />        <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.FastJsonHttpMessageConverter4" >            <!--加入支持的媒体类型,返回contentType-->            <property name="supportedMediaTypes">                <list>                    <!--这里顺序不能反,一定要先写text/html,不然IE下会出现下载提示-->                    <value>text/html;charset=UTF-8</value>                    <value>application/json;charset=UTF-8</value>                </list>            </property>        </bean>    </mvc:message-converters></mvc:annotation-driven>

使用fastjson和Jackson的区别如下:

下面的请求代码:

@ResponseBody@RequestMapping("/testJson")public Map<String, Object> testJson(String id) {    Map<String, Object> map = new HashMap<>();    Map<String, Object> data = new HashMap<>();    data.put("id", id);    map.put("result", 0);    map.put("message", "成功 success");    map.put("data", data);    return map;}

访问的时候如果不传id参数,http://localhost:8080/demo/testJson

fastjson返回:

{"result": 0,"data": {},"message": "成功 success"}

jackson返回:

{"result": 0,"data": {"id": null},"message": "成功 success"}
原创粉丝点击