Java技巧——将前端的对象数组通过Json字符串传到后端并转换为对象集合
摘要:本文主要记录了如何将将前端的对象数组通过Json字符串传到后端,并在后端将Json字符串转换为对象集合。
前端代码
前端代码的功能是获取页面上的学生信息,使用对象数组保存,将对象数组转换为Json字符串传递到后端:
1 var students = $("#studentList .item"); 2 var studentList = []; 3 for (var i = 0; i < students.length; i++) { 4 var student = {}; 5 student["name"] = $(students[i]).attr("name"); 6 student["sex"] = $(students[i]).attr("sex"); 7 student["age"] = $(students[i]).attr("age"); 8 studentList.push(drug); 9 } 10 var drugListStr = JSON.stringify(studentList); 11 ajaxAsyncUtil(drugListStr, mainpath + "/student/addStudentList.do", function (response) { 12 alert("操作成功"); 13 });
后端代码
后端代码的功能是获取前端传入的Json字符串,并解析为对象集合进行遍历:
1 @RequestMapping(value = "addStudents.do") 2 public void addStudents(HttpServletRequest request, HttpServletResponse response, String callback, String studentListStr) throws Exception { 3 //String studentListStr = "[{"name":"张三","sex":"男","age":"20"},{"name":"李四","sex":"女","age":"25"},]"; 4 List<Student> studentList = JSONObject.parseArray(studentListStr, Student.class); 5 for (Student student : studentList) { 6 System.out.println(student.getName()); 7 } 8 }
其中,在后端使用的转换是来自于 com.alibaba.fastjson 包下的类。