SpringMVC中使用JSON

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/T_P_F/article/details/80100837

前台发送:

  • 传递JSON对象
function requestJson(){
    $.ajax.({
        type : “post”,
        url : “${pageContext.request.contextPath}/testJson/responseJson”,
        contextType : “application/x-www-form-urlencoded;charset=utf-8”,//默认值
        data : ‘{“username” : “name “, “gender” : “male”}’,
        dataType : “json”,
        success:function(data){
    console.log(“服务器处理过的用户名是:”  + data.username);
    console.log(“服务器处理过的性别是:” + data.gender);
}
});
}
  • 传送JSON字符串
function requestJson(){
    var json = {“username” : “name “, “gender” : “male”};
    var jsonstr = JSON.stringify(json);//json对象转换json字符串
    $.ajax.({
        type : “post”,
        url : “${pageContext.request.contextPath}/testJson/responseJson”,
        contextType : “application/json;charset=utf-8’
traditional:true,//这使json格式的字符不会被转码,
        data : jsonstr,
        dataType : “json”,
        success:function(data){
            console.log(“服务器处理过的用户名是:”  + data.username);
            console.log(“服务器处理过的性别是:” + data.gender);
        }
    });
}

下面介绍以上参数的含义:
type:Http请求的方式,一般使用POST和GET
url:请求的url地址,也就是我们所要请求的Controller的地址
contextType:这里要注意,如果使用的是key/value值,那么这个请求的类型应该是application/x-www-form-urlencoded/charset=utf-8,该值也是默认值。
如果是JSON格式的话应该是application/json;charset=utf-8
traditional:若一个key是个数组,即有多个参数的话,可以把该属性设置为true,这样就可以在后台可以获取到这多个参数。
data:要发送的JSON字符串
success:请求成功之后的回调函数
error:请求失败之后的回调函数

SpringMVC需要的jar包:jackson-core-asl-x.x.xx.jar、jackson-mapper-asl-x.x.xx.jar
SpringMVC配置文件中添加:

后台接收

  • 接收JSON对象
    Controller控制器中的方法
    ①直接获取就行
@RequestMapping("/requestJson")
public @ResponseBody Person requestJson(Person p) {
System.out.println("json传来的串是:" + p.getGender() + " " + p.getUserName() + " " +p.isAdalt());
p.setUserName(p.getUserName().toUpperCase());
return p;
}
Person的实体类:
public class Person {
    private String userName;
    private String gender;
    private boolean adalt;
}
  • 接收JSON字符串
@RequestBody(接收的是JSON的字符串而非JSON对象),注解将JSON字符串转成JavaBean
@ResponseBody注解,将JavaBean转为JSON字符串,返回到客户端。具体用于将Controller类中方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据,比如JSON和XML等,通过Response响应给客户端。produces=”text/plain;charset=utf-8”设置返回值。
②把JSON字符串发送过来,使用注解@RequestBody接收String字符串之后,再解析出来
@RequestMapping(value = "testAjax.action",method = RequestMethod.POST) 
public void testAjax(@RequestBody String jsonstr){ 
JSONObject jsonObject = JSONObject.parseObject(jsonstr);//将json字符串转换成json对象 String age = (String) jsonObject.get("age");//获取属性 
System.out.println(age); 
}

③当然也可以使用Map集合
@RequestMapping("/jsontest")
public void test(@RequestBody Map map){
    String username = map.get("username").toString();
    String password = map.get("password").toString();
}

猜你喜欢

转载自blog.csdn.net/T_P_F/article/details/80100837
今日推荐