3

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.

1 Answer 1

6

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){
Sign up to request clarification or add additional context in comments.

1 Comment

JSON was invalid. Correcting it worked and also wrapped List of customers in a different class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.