前端:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>submitUserList_3</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script th:src="@{/resources/js/js/jquery-3.3.1.min.js}"></script>
<script type="text/javascript" language="JavaScript"> function submitUserList_3() {alert("ok"); var customerArray = new Array(); //customerArray.push({id: "1", name: "李四", pwd: "123"}); //customerArray.push({id: "2", name: "張三", pwd: "332"}); //customerArray.push({title:"標題一",type:2,options:[{option:"選項一"},{option:"選項二"}]});
customerArray.push({type:"",title:"",url:"",content:"",endTime:"",questionModels:[{title:"標題一",type:2,options:[{option:"選項一"},{option:"選項二"}]}]}); //customerArray.push({title:"標題二",shareId:1,type:2,option:"選項一,選項二"}); //customerArray.push({title:"標題二",type:2,options:[{option:"1"},{option:"2"}]});
$.ajax({ url: "./questionShare", type: "POST", contentType : 'application/json;charset=utf-8', //設置請求頭信息
dataType:"json", data: JSON.stringify(customerArray), //將Json對象序列化成Json字符串,JSON.stringify()原生態方法 //data: $.toJSON(customerArray), //將Json對象序列化成Json字符串,toJSON()需要引用jquery.json.min.js
success: function(data){ alert(data); }, error: function(res){ alert(res.responseText); } }); } </script>
</head>
<body>
<h1>submitUserList_3</h1>
<input id="submit" type="button" value="Submit" onclick="submitUserList_3();">
</body>
</html>
注:上面嵌套了多個對象:
({type:"",title:"",url:"",content:"",endTime:"",questionModels:[{title:"標題一",type:2,options:[{option:"選項一"},{option:"選項二"}]}]})
最外層對象
public class Share {
private Integer id;
private Integer type;
private String title;
private String url;
private String content;
private String time;
private String endTime;
private List<QuestionModel> questionModels;
}
---
questionModels對象:
public class QuestionModel{
private Integer id; //標識符
private String title; //標題
private Integer type; //分享類型
private List<Option> options; //選項
}
----
Options對象
public class Option {
private String option;
}
---
后台接收對象
@RequestMapping("/questionShare")
@ResponseBody
public String getTest3(@RequestBody List<Share> shares){
System.out.println("記錄數:"+shares.size());
return "success";
}
[{"type":"1","title":"母親節","url":"","content":"","endTime":"","questionModels":[{"title":"標題一","type":2,"options":[{"option":"選項一"},{"option":"選項二"}]}]}]。
--------------
如果用字符串接收,這是數組類型,需要將"[]"去掉在轉換為Java對象
@RequestMapping("updateShare")
@ResponseBody
public AjaxResult update(@RequestBody String string){
System.out.println("接收的參數:"+ string );
JSONObject jsonObject = JSONObject.parseObject(string);
Share share = JSON.toJavaObject(jsonObject,Share.class );
int result = shareService.update(share);
if(result > 0){
return AjaxResult.ok();
}else{
return AjaxResult.build("false",null );
}
}
dd