如何在 jersey Rest Webservice 中接受 json 数组输入

how to accept json array input in jersey Rest Webservice

正在使用 Jersey.Am 对 Web 服务略微陌生的方式开发休息 Web 服务。我需要将客户列表作为输入传递给 rest webservice。在实现它时遇到问题。

下面是我的客户对象class

@Component
public class customer {
private String customerId;
private String customerName;

我的终点如下。 addCust 是将在调用 web 服务时调用的方法

    @Path("/add")
    @Produces({MediaType.APPLICATION_JSON})
    @Consumes({MediaType.APPLICATION_JSON})
    public String addCust(@Valid customer[] customers){

    //And json input is as below
    {customers:{"customerId":"1","customerName":"a"},
    {"customerId":"2","customerName":"b"}}

但是球衣无法将 json 数组转换为客户数组。它返回 400。日志显示 "no viable alternative at c"。如何将 Json 数组作为输入传递给 webservice 并转换为 Array 或 ArrayList。任何帮助表示赞赏。

您的 json 无效,字段名称应始终用双引号引起来,数组放在 [] 内 例如:

{"customers":[{"customerId":"1","customerName":"a"},
{"customerId":"2","customerName":"b"}]}

这就是杰克逊无法解组它的原因。但是这个 json 永远不适合你的 api。 这是您应该发送的示例:

[{"customerId":"1","customerName":"a"},{"customerId":"2","customerName":"b"}]

另一件事是您可以使用集合而不是数组:

@Path("/add")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public String addCust(@Valid List<Customer> customers){

如果你想发送这样的 json:

{"customers":[{"customerId":"1","customerName":"a"},
{"customerId":"2","customerName":"b"}]}

然后你必须将所有内容包装到 class 和 "customers" 属性:

class AddCustomersRequest {
  private List<Customer> customers;

  public void setCustomers(List<Customer> customers) {
      this.customers = customers;
  }

  public void getCustomers() {
     return this.customers;
  }
}

并在您的 API:

中使用它
@Path("/add")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public String addCust(@Valid AddCustomersRequest customersReq){