@RequestBody接收ajax的json字串

來源:互聯網
上載者:User

標籤:sys   app   int   使用   object   return   ping   字串轉換   pre   

在使用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";    }

 

@RequestBody接收ajax的json字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.