Search code examples
javajsonrestjax-rsjersey-2.0

post method does not get payload object


I have the following POJO:

public class Order {

    private String orderCode;

    // And many more ... getters and setter

}

And the following REST resource:

@Path("/customers/{customercode}/orders")
public class OrderResource {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response create(@PathParam("customercode") String customerCode, Order order) {
        // ...
    }

    // ...
}

Now some client sends an Order object as JSON to this URL. The customerCode parameter gets set to the expected value, but the order parameter is null, although here is a valid JSON body in the request. (I can see it in the ContainerRequestContext object.)

Jersey's log says nothing about any problems (even in DEBUG mode).

Any ideas? TIA! (I am using Jersey 2 with Jackson)


Solution

  • So in your filter you are reading the InputStream from the ContainerRequestContext. So now the stream is empty. That means no data left for when the method param deserialization is done.

    One way around this is to buffer the entity before reading it. We can do that by casting the ContainerRequestContext to ContainerRequest, which will give us many more methods to interact with the context.

    @Override
    public void filter(ContainerRequestContext requestContext) {
        ContainerRequest containerRequest = (ContainerRequest)requestContext;
        containerRequest.bufferEntity();
        Order order = containerRequest.readEntity(Order.classs);
        // or
        InputStream in = containerRequest.readEntity(InputStream.class);
    }
    

    The call to bufferEntity() will do exactly what the method name implies. Also if you are familiar with working with the client API, the readEntity should look familiar. It works pretty much the same way as Response.readEntity(...). It looks for a MessageBodyReader for the inbound Content-Type. The MessageBodyReader for InputStream doesn't do anything special, but just return the orginal stream. So if you need it, there it is.