在SpringMVC和SpringBoot中,我们有这样一个场景,就是接受前端复杂的对象数组,或者多个数组。这是我们可以用@RequestBody
注解,来解析请求体中的数据。但是值得注意的是在GET
请求是不能进行该种方式的操作,因为GET
请求没有请求体。下面就搭建一个简单的demo进行展示:
一、 数据准备
1.1 json数据准备
# 第一段json数据
[
{
"id": "xxxx",
"goodsId": "1001",
"name": "苹果手机",
"number": 1
}, {
"id": "xxxx",
"goodsId": "1002",
"name": "华为手机",
"number": 2
}
]
# 第二段json数据
{
"orderId": "11xxcqdffvf",
"order": [
{
"id": "xxxx",
"goodsId": "1001",
"name": "苹果手机",
"number": 1
},
{
"id": "xxxx",
"goodsId": "1002",
"name": "华为手机",
"number": 2
}],
"stock": [
{
"id": "xxxx",
"goodsId": "1001",
"name": "苹果手机",
"number": 1
},
{
"id": "xxxx",
"goodsId": "1002",
"name": "华为手机",
"number": 2
}]
}
1.2 编写实体对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Product {
private String id;
private String goodsId;
private String name;
private int number;
}
1.3 搭建一个SpringMVC或者SpringBoot项目,这里搭建一个SpringBoot项目
二、编写测试
2.1 一个对象数组的请求
2.1.1 前端数据请求编写
$.ajax({
type: "put",
url: "http://localhost:8080/test/save",
contentType: 'application/json;charset=utf-8',
data: JSON.stringify([
{
"id": "xxxx",
"goodsId": "1001",
"name": "苹果手机",
"number": 1
}, {
"id": "xxxx",
"goodsId": "1002",
"name": "华为手机",
"number": 2
}
]),
success: function (res) {}
});
2.1.2 编写后端接口
@RestController
@RequestMapping("/test")
public class OrderController {
// 创建订单
@PutMapping("/save")
public Object createOrder(@RequestBody List<Product> productList) {
return productList;
}
}
2.2 多个对象数组请求
2.2.1 前端数据请求编写
$.ajax({
type: "put",
url: "http://localhost:8080/test/save",
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({
"orderId": "11xxcqdffvf",
"order": [
{
"id": "xxxx",
"goodsId": "1001",
"name": "苹果手机",
"number": 1
},
{
"id": "xxxx",
"goodsId": "1002",
"name": "华为手机",
"number": 2
}],
"stock": [
{
"id": "xxxx",
"goodsId": "1001",
"name": "苹果手机",
"number": 1
},
{
"id": "xxxx",
"goodsId": "1002",
"name": "华为手机",
"number": 2
}]
}),
success: function (res) {
}
});
2.2.2 后端编写
@RestController
@RequestMapping("/test")
public class OrderController {
@PutMapping("/save1")
public Object createOrder1(@RequestBody Map<String, Object> map) {
return map;
}
}
2.3 注意事项
- 发送的请求类型不能是
GET
请求,可以POST
,PUT
,DELETE
等请求。- 前端发送数据的时候,请求内容格式必须设置为
contentType:'application/json;charset=utf-8'
,默认是``contentType:‘www-form-urlencoded’`\- 上传的数据必须使用
JSON.stringify(..)
处理- 后端接受参数前需要加注解
@RequestBody
,且每一个请求的参数里面最多只能有一个该注解