標籤: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字串