Search code examples
javaweb-servicesjerseyserver-sidejersey-2.0

Java Jersey server not getting POST parameters


I am using Java Jersey on the server side and I am using a @BeanParam to collect the POST parameters via JSON, but the @BeanParam class is just not getting them.

The API:

@POST
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public Response sync(@BeanParam SyncRequestParams request) {
         .........
}

The @BeanParam class :

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class SyncRequestParams {
   @JsonProperty("id")
   private int id;
}

So if the client POSTs a JSON like:

{
  "id": 12345
}

The SyncRequestParams will still have id as 0, and not 12345

What did I not do right here?

Thanks IS


Solution

  • The @BeanParam cannot be used to map a JSON payload to a bean.

    Using @BeanParam requires the bean fields to be annotated with jax-rs param annotations (@FormParam, @QueryParam, etc.). The runtime then creates a bean and populates the fields with the param values. Since your id has no parameter annotation (and the request does not contain such a parameter) it is still 0.

    What you want is that the JSON payload of the POST request is parsed to an instance of SyncRequestParams and therefore you should simply write

    @POST
    @Produces({MediaType.APPLICATION_JSON})
    @Consumes({MediaType.APPLICATION_JSON})
    public Response sync(SyncRequestParams request) {