前言
-簡單數組請前往:[https://blog.csdn.net/shuai8624/article/details/106026325](https://blog.csdn.net/shuai8624/article/details/106026325)
-本節總結數組對象 如 let array=[{"id":1,"name":"張一"},{"id":2,"name":"張二"},{"id":3,"name":"張三"}];
一. 示例採用的技術
前端: jquery, ajax請求(axios應該也差不多,自己看着玩)
後端: SpringBoot
二. 直接上才藝
目前總結了2種方式,各位大佬給補充下吧:
1)前端轉JSON字符串,後端String接口,json解析成Java對象
前端:
//方式一:轉成json字符串, 後端接口string去接收,然後再轉成JSON數組處理
//contentType爲默認值,即 application/x-www-form-urlencoded
function array1() {
let array=[{"id":1,"name":"張一"},{"id":2,"name":"張二"},{"id":3,"name":"張三"}];
$.ajax({
url: "http://localhost:8080/array1",
data: {
"userList": JSON.stringify(array)
},
type: "post",
success: function (data) {
alert(data)
},
})
};
後端接口:(json字符串轉對象的邏輯自己寫)
@RequestMapping("/array1")
public String array1(String userList) {
return userList;
}
2)前端整個data直接傳 json字符串,後臺接口用@RequestBody List ids 接收
前端
//方式二: 前端整個data直接傳 json字符串,後臺接口用@RequestBody List<Integer> ids 接收
//contentType必須值爲: "application/json"
function list1() {
let array=[{"id":1,"name":"張一"},{"id":2,"name":"張二"},{"id":3,"name":"張三"}];
$.ajax({
url: "http://localhost:8080/list2",
data: JSON.stringify(array),
type: "post",
dataType: "json",
contentType:"application/json",
success: function (data) {
alert(data)
},
})
};
後端: List或者數組去接收都可以
@RequestMapping("/list1")
public Integer list1(@RequestBody List<User> user) {
return user.size();
}
//或者
@RequestMapping("/list2")
public Integer list2(@RequestBody User[] user) {
return user.length;
}
三. 注意
1、contentType別傳錯了,示例中沒傳的,使用的是默認值:application/x-www-form-urlencoded
2、如果遇到別的問題或者別的解決方法,可以聯繫我一下,做個補充