Java 将json对象传递给使用spring开发的端点
我有一个使用spring.io创建的端点。下面可以看到我的GetMapping声明Java 将json对象传递给使用spring开发的端点,java,spring-mvc,Java,Spring Mvc,我有一个使用spring.io创建的端点。下面可以看到我的GetMapping声明 @ApiOperation( value = "Returns a pageable list of CustomerInvoiceProducts for an array of CustomerInvoices.", notes = "Must be authenticated.") @EmptyNotFound @GetMapping({ "customers
@ApiOperation(
value = "Returns a pageable list of CustomerInvoiceProducts for an array of CustomerInvoices.",
notes = "Must be authenticated.")
@EmptyNotFound
@GetMapping({
"customers/{customerId}/getProductsForInvoices/{invoiceIds}"
})
public Page<CustomerInvoiceProduct> getProductsForInvoices(
@PathVariable(required = false) Long customerId,
@PathVariable String[] invoiceIds,
Pageable pageInfo) {
//Do something fun here
for (string i: invoiceIds){
//invoiceIds is always empty
}
}
InvoiceId的字符串数组在for循环中始终为空,不会向数组传递任何内容。我做错了什么?您使用的映射是:
customers/{customerId}/getProductsForInvoices/{invoiceIds}
customerId和InvoiceID在这里都是路径变量
http://localhost:8030/api/v1/customers/4499/getProductsForInvoices/invoiceIds/
您正在拨打的电话包含customerId,但没有InvoiceID。或者,您可以将列表作为字符串而不是InvoiceID传递,并将其作为字符串读取,然后通过分解列表来创建列表,这将是一种糟糕的做法
另一种方法是将path变量-invoiceId更改为RequestBody
通常情况下,路径变量用于单个id或在某些结构化数据中导航。当您想要处理一组ID时,推荐的做法是在Post方法调用中将它们作为RequestBody传递,而不是在Get方法调用中传递
REST API的示例代码段(post调用):
这里,假设您试图将Employee对象传递给POST调用,RESTAPI将如下所示
@PostMapping("/employees")
Employee newEmployee(@RequestBody Employee newEmployee) {
//.. perform some operation on newEmployee
}
此链接将使您更好地了解如何使用RequestBody和PathVariables-
为什么您认为JSON请求主体会以某种方式填充带注释的参数
@PathVariable
?如果我知道,我不会发布这个问题。您提供的映射和您提供的邮递员呼叫彼此不匹配。没有/invoiceIds/
映射。它在哪里?我不明白,我正试着理解你的困惑是从哪里来的,这样我就可以根据你的困惑来调整我的答案。你为什么这样写代码?您打算让@PathVariable
做什么?你以为邮递员会去哪里?为什么?请编辑您的问题并包含这些详细信息。我遵照您的建议,使用帖子更改为RequestParam。我得到的错误是“不允许使用方法”,“不支持请求方法发布”您好,您可以使用这个Spring链接本身来创建REST API-很抱歉,发布JSON数据时,他不需要使用@RequestBody
吗?这也会起作用,我提供的第二个链接使用了它。
http://localhost:8030/api/v1/customers/4499/getProductsForInvoices/invoiceIds/
@PostMapping("/employees")
Employee newEmployee(@RequestBody Employee newEmployee) {
//.. perform some operation on newEmployee
}