@RequestBody接收ajax的json字符串

在使用ajax进行请求,并传递参数时,偶尔需要把数组作为传递参数,这是就要使用@RequestBody来解决这个问题

在页面端的处理:

(1)利用JSON.stringify(arr)需要把json对象数组转变成一个json对象字符串
(2)在ajax的参数中设置"contentType": "application/json"

  $(function(){
         $("#exe").on("click",function(){
            var arr = new Array();
            arr.push({"name":"lcs","age":18});
            arr.push({"name":"yds","age":19});
            arr.push({"name":"hrl","age":20});
            arr.push({"name":"lyf","age":21});
            var arrs = JSON.stringify(arr);
            $.ajax({
                "url": "ajax_array.do",
                "type": "post",
                "data": arrs,
                "contentType": "application/json",
                "dataType": "json",
                "success": function(result){
                    alert("请求成功!");
                },
                "error": function(){
                    alert("请求失败!");
                }
            });
        }); 
    });

在后端的处理:

(1)利用RequestBody来接收JSON对象字符串,persons中是json对象数组进JSON.stringify(arr)转换的JSON对象字符串(数组的json对象字符串)

(2)导入json-lib,利用其JSONArray和JSONObject的方法来解析获取JSON对象字符串中的数据

(3)JSONArray.fromObject(persons)是把JSON对象字符串转换成JSON对象。

  @ResponseBody
    @RequestMapping("/ajax_array.do")
    //@RequestBody接收ajax请求的json字符串参数
    public String getPersons(@RequestBody Person[] persons){
        //将persons JSON字符串转换成JSON对象
        //JSONArray对象,有点像list对象
        JSONArray arrs = JSONArray.fromObject(persons);
        List<Person> personList = new ArrayList<Person>();
        //遍历JSONArray
        for(int i=0; i<arrs.size(); i++){
            Person person = new Person();
            //getJSONObject(i)是一个json对象
            String name = arrs.getJSONObject(i).getString("name");
            int age = arrs.getJSONObject(i).getInt("age");
            person.setName(name);
            person.setAge(age);
            personList.add(person);
        }
        System.out.println(personList);
        return "success";
    }