HTML代码
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 引入jquery插件 --> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js" type="text/javascript"></script> <title>集合测试</title> </head> <body> <h1>json转集合</h1> <button onclick="submitForm();">提交</button> </body> <script type="text/javascript"> function submitForm(){ var users = new Array(); users.push({name: "李四",password: "123"}); users.push({name: "张三",password: "332"}); $.ajax({ type: "POST", url: "saveUsers", data: JSON.stringify(users),//将对象序列化成JSON字符串 dataType:"json", contentType : 'application/json;charset=utf-8', //设置请求头信息 success: function(data){ alert(111); }, error: function(res){ } }); } </script> </html>
User.java
/** * 类描述 * @author xiaofei.xian * 日期:2017年10月25日 下午3:51:19 */ public class User { private String name; private String password; /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the password */ public String getPassword() { return password; } /** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } }
Controller代吗:
/** * 类描述 * @author xiaofei.xian * 日期:2017年10月25日 下午3:12:39 */ @Controller @RequestMapping("${adminPath}/test") public class JsonToObjectController { @RequestMapping(value="index") public String index(){ return "modules/order/index"; } @RequestMapping(value = "saveUsers") @ResponseBody public Object saveUser(@RequestBody ArrayList<User> users) { Map<String, Object> reMap = new HashMap<String, Object>(); for (User user : users) { System.err.println(user.getName() + ":" + user.getPassword()); } reMap.put("success", true); reMap.put("msg", "json转换成功!"); return reMap; } }