[英]Spring rest api same url for bulk and single request
I would like to have this API in a Spring boot app:我想在 Spring 启动应用程序中有这个 API:
POST /items发布/项目
{
"name": "item1"
}
POST /items发布/项目
[
{
"name": "item1"
},
{
"name": "item2"
},
]
So the same endpoint could accept array or a single element in a json body.因此,同一端点可以接受 json 主体中的数组或单个元素。
Unfortunatelly this doesn't work:不幸的是,这不起作用:
@PostMapping(path="items")
public ResponseEntity<String> items(@RequestBody Item item) {}
@PostMapping(path="items")
public ResponseEntity<String> items(@RequestBody List<Item> items) {}
I also tried this:我也试过这个:
@PostMapping(path="items")
public ResponseEntity<String> items(@RequestBody @JsonFormat(with= JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) List<Item> items) {}
it doesn't work.它不起作用。
If I wrap the list like:如果我像这样包装列表:
public class Items {
@JsonFormat(with= JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private List<item> items;
}
then unfortunately my request body would look like:那么不幸的是,我的请求正文将如下所示:
{
"items": [
{
"name": "item1"
},
{
"name": "item2"
},
]
}
Do you know how I can have such API with spring boot?你知道我怎么能有这样的 API 和 spring 引导?
You want a variable that can directly hold an Array or an Object.您需要一个可以直接保存数组或 Object 的变量。 There is no straightforward way to achieve something like that because of the Static Typing restrictions of Java.由于 Java 的 Static 类型限制,没有直接的方法可以实现类似的目标。
The only way I can imagine so far to achieve something like this is to create a single API that takes some generic type.到目前为止,我能想象到的唯一方法是创建一个采用某种通用类型的 API。
Like an Object
:像Object
:
@PostMapping(path="items")
public ResponseEntity<String> items(@RequestBody Object body) {
if(body instanceof List) {
} else {
}
}
Or a String
:或String
:
@PostMapping(path="items")
public ResponseEntity<String> items(@RequestBody String body) {
if(body.charAt(0) == '[' && body.charAt(body.length() - 1) == ']') {
} else if(body.charAt(0) == '{' && body.charAt(body.length() - 1) == '}') {
} else {
}
}
You'll have to do a lot of work manually.您将不得不手动完成大量工作。
Also, you can't create two APIs with the same path /items
and the same method POST
, they will raise a compile-time error.此外,您不能创建具有相同路径/items
和相同方法POST
的两个 API,它们会引发编译时错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.