SpringMVC框架 -- json数据交互

作者: Mr_欢先生 | 来源:发表于2017-09-28 21:59 被阅读183次

一.JSON简单介绍:

参考笔记:JSON简单快速入门

二.json数据交互

请求json 输出json 需要请求数据为json,需要在前端转为json不太方便。不常用
请求key/value、输出json。常用

  • 1.环境搭建

下载jar包
jackson-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar

<!--json包-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.7.2</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
  • 2.配置json转换器
<!--注解适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
    <list>
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
    </list>
    </property>
</bean>
  • 注意如果使用<mvc:annotation-driven />则不用定义上边的内容。

三测试

  • 输入json串,输出json串
 function requestJson(){
        $.post({
            type:'post',
            url:'/json/requestJson',
            contentType:'application/json;charset=utf-8',
            data:'{"userName":"小明","passWord":"123456"}'
        },function (data) {
            console.log(data);
        });
    }

jsonControllar.java处理

package com.huan.web.json;


import com.huan.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/json")
public class jsonControllar {
    //将接受过来的json对象处理完,转为json返回
    @RequestMapping("/requestJson")
    public @ResponseBody User requestJson(@RequestBody User user){

        return user;
    }
}
  • 输入key/value,输出json串
function responseJson(){
        $.post({
            type:'post',
            url:'/json/responseJson',
            data:"userName=小明&passWord=123456"
        },function (data) {
            console.log(data);
        });

jsonControllar.java处理

package com.huan.web.json;


import com.huan.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/json")
public class jsonControllar {
    //将接受过来的key/value对象处理完,转为json返回
    @RequestMapping("/responseJson")
        public @ResponseBody User responseJson(User user){
            return user;
        }
}

相关文章

网友评论

    本文标题:SpringMVC框架 -- json数据交互

    本文链接:https://www.haomeiwen.com/subject/gzpvextx.html