【问题标题】:how to accept json array input in jersey Rest Webservice如何在 jersey Rest Webservice 中接受 json 数组输入
【发布时间】:2015-12-07 05:37:12
【问题描述】:

我正在使用 Jersey 开发一个 REST Web 服务。我对 Web 服务有点陌生。我需要将客户列表作为输入传递给休息网络服务。在实现它时遇到问题。

下面是我的客户对象类

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

但是 jersey 无法将 json 数组转换为客户数组。它返回 400。日志显示“c 处没有可行的替代方案”。如何将 Json 数组作为输入传递给 Web 服务并转换为 Array 或 ArrayList。任何帮助表示赞赏。

【问题讨论】:

    标签: java json web-services rest jersey


    【解决方案1】:

    您的 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"}]}
    

    那么你必须用“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){
    

    【讨论】:

    • JSON 无效。更正它有效,并将客户列表包装在不同的类中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    相关资源
    最近更新 更多