how to accept json array input in jersey Rest Webservice

14,703

Your json is invalid, field names should be always double quotted, and arrays are placed inside [] for example:

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

thats why jackson cannot unmarshall it. But this json will never fit your api. Here is an example of what You should send:

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

Another thing is that You can use collections instead of arrays:

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

If you want to send a json like this:

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

then you have to wrap everything into class with "customers" property:

class AddCustomersRequest {
  private List<Customer> customers;

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

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

And use it in Your API:

@Path("/add")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public String addCust(@Valid AddCustomersRequest customersReq){
Share:
14,703
RK3
Author by

RK3

Updated on June 04, 2022

Comments

  • RK3
    RK3 almost 2 years

    Am developing a rest webservice using Jersey.Am slightly new to webservices. I need to pass List of customer as input to rest webservice. having issue in achieving it.

    Below is my customer object class

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

    And my endpoint is as below. addCust is the method that will be called on calling the webservice

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

    But jersey is not able to convert json array to Array of Customers. It is returning 400. And the logs shows "no viable alternative at c". How to pass Json array as input to webservice and convert into Array or ArrayList. Any help appreciated.