springmvc使用fastjson

springmvc使用fastjson

1、导包

 <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.58</version>
    </dependency>

2、配置文件

 <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json</value>
                        <value>application/xml;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

3、jsp代码

<script>
    $(function () {
        $.ajax({
            url:"${pageContext.servletContext.contextPath}/user/json",
            data:JSON.stringify({username:"tom"}),//JSON.stringify()必须有,否则只会当做表单的格式提交
            dataType:"json",
            type:"post",
            contentType:"application/json;charset=utf-8",//如果想以json格式把数据提交到后台的话,这个必须有,否则只会当做表单提交
            success:function (data) {
                alert(data.username);
            }
        });
    });
</script>

4、控制器代码

@RequestMapping("/json")
    public @ResponseBody User jsonToObject(@RequestBody User user){
        System.out.println("--------");
        System.out.println(user);
        return user;
    }
上一篇:fastjson到底做错了什么?为什么会被频繁爆出漏洞?


下一篇:scala json fastjson json4s