有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将json对象传递给使用spring开发的端点

我有一个使用spring创建的端点。木卫一。下面可以看到我的GetMapping声明

@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
        }
}

下面是我如何从postman调用url并传递数据

http://localhost:8030/api/v1/customers/4499/getProductsForInvoices/invoiceIds/
{
  "invoiceIds": [
    "123456",
    "234566",
    "343939"
  ]
}

InvoiceId的字符串数组在for循环中始终为空,不会向数组传递任何内容。我做错了什么


共 (1) 个答案

  1. # 1 楼答案

    您正在使用的映射如下所示:

    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- https://javarevisited.blogspot.com/2017/10/differences-between-requestparam-and-pathvariable-annotations-spring-mvc.html

    https://spring.io/guides/tutorials/rest/