Post method does not receive 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 is sending the object Order

as JSON to this url. The parameter is customerCode

set to the expected value, but the parameter Order

is equal null

even though a valid JSON body is present in this request. (I can see it in the object ContainerRequestContext

.)

Jersey magazine says nothing about any issues (even in DEBUG mode).

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

+3


source to share


1 answer


So, in your filter, you read InputStream

from ContainerRequestContext

. So now the stream is empty. This means that there is no data left when the method parameters are deserialized.

One way is to buffer the object before reading it. We can do this by translating ContainerRequestContext

to ContainerRequest

, which will give us many more methods for interacting 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 bufferEntity()

will do exactly what the method name implies. Also, if you are familiar with working with the client API, it readEntity

should look familiar. It works in much the same way as Response.readEntity(...)

. It looks MessageBodyReader

for the incoming Content-Type. MessageBodyReader

forInputStream

does nothing special, it just returns the original stream. So if you need it, this is it.

+3


source







All Articles