spring MVC 如何接收前台传入的JSON对象数组
spring MVC 如何接收前台传入的JSON对象数组
主要方法:
(主要用到的包是 net.sf.json 即:json-lib-2.3-jdk15.jar
完整相关jar包:
commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-lang-2.4.jar
commons-logging-1.1.jar
ezmorph-1.0.4.jar
json-lib-2.2.2-jdk15.jar)
转换JSONArray json数组为实体类的List:
1 //T是随便定义的泛型,你根据自己需要自己定义类型 2 //doList是json类型字符串 3 public List<T> doList(String doList){ 4 JSONArray jsonArray=JSONArray.fromObject(doList); 5 List<T> list=(List)JSONArray.toCollection(jsonArray,T.class); 6 return list; 7 }
迭代json数组:
1 Iterator<Object> it = jsonArray.iterator(); 2 while (it.hasNext()) { 3 JSONObject ob = (JSONObject) it.next(); 4 }
------
------
具体代码:
js代码:
1 function submitUserList() { 2 alert("ok"); 3 var customerArray = new Array(); 4 customerArray.push({id: "1", name: "李四", pwd: "123"}); 5 customerArray.push({id: "2", name: "张三", pwd: "332"}); 6 7 $.ajax({ 8 url: "/user/submitUserList_3", 9 type: "POST", 10 dataType:"json", 11 data: { 12 //"doList":JSON.stringify(customerArray), //将Json对象序列化成Json字符串,JSON.stringify()原生态方法 13 "doList":$.toJSON(customerArray) 14 }, //将Json对象序列化成Json字符串,toJSON()需要引用jquery.json.min.js 15 success: function(data){ 16 }, 17 error: function(res){ 18 alert(res.responseText); 19 } 20 }); 21 }
java代码:
方法一:
1 ///若接收的参数可以被封装到javabean对象中则可以如下写: 2 public List < User> doList(String doList) { 3 //先把字符串转成JSONArray 4 JSONArray jsonArray = JSONArray.fromObject(doList); 5 //再把jsonArray转成对象集合 6 List < User > list = (List) JSONArray.toCollection(jsonArray, User.class); 7 return list; 8 } 9
--------
方法二:
1 ///若接收的参数不方便被封装到java对象中,则可以用下面方式获取 2 public List < User> doList(String doList) { 3 //先把字符串转成JSONArray 4 JSONArray jsonArray = JSONArray.fromObject(doList); 5 //迭代jsonArray 6 Iterator<Object> it = jsonArray.iterator(); 7 List<User> list=new ArrayList<User>(); 8 while (it.hasNext()) { 9 JSONObject ob = (JSONObject) it.next();//取到每个JSONObject对象 10 User user = null; 11 if(ob.getString("id")!=null){//调用JSONObject的getString("属性")方法获取对应值 12 user=new User(); 13 user.setId(ob.getString("id")); 14 } 15 if(ob.getString("name")!=null){ 16 user.setName(ob.getString("name")); 17 } 18 if(user!=null){ 19 list.add(user); 20 } 21 } 22 return list; 23 }