0

I'm using Moxy in my Jersey (2.7) project basically just to marshall my objects to JSON when the service issues a response. It works fine, but now I am also using ContainerResponseFilter to make some changes on every response issued and I am not sure how to unmarshall the content of the request body into an object, which is something I need.

Specifically:

  • i've just registered Moxy in a ResourceConfig instance: register(MOXyJsonProvider.class)
  • a class is using JAXB annotations, so when I set an instance of the class in Response.entity() it gets transformed into JSON properly
  • the request body (also JSON) also gets unmarshalled into an object when I set it as a method paramether, for instance:

    @Consumes(MediaType.APPLICATION_JSON) public Response getSomething( MyClass instance ) {

However inside a ContainerResponseFilter I can access the request body like so,

InputStream body = requestContext.getEntityStream()

but I'm not sure if it's possible to have this also automatically converted into an object. The information I need is relatively simple, so I guess I could parse JSON in another way, but I'm curious.

I've tried searching, but I didn't find it.

nomve
  • 736
  • 4
  • 14

1 Answers1

1

In your ContainerReponseFilter, you can do something like this:

public class ApplicationResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(final ContainerRequestContext request,
        final ContainerResponseContext response) throws IOException {

        // your code
        response.getEntity();

    }
}

which converts it to your object with JAXB annotations. I was not doing it in my responseFilter, but I've just debugged it and it works.

lrnzcig
  • 3,868
  • 4
  • 36
  • 50
  • This is exactly what I am doing and actually it helps me, so thanks a lot. I forgot I already had the object in my response, long day yesterday. But generally do you know if it's however possible to unmarshall an InputStream from the request body? – nomve May 22 '14 at 08:44
  • sorry, you meant the request in the first place, and I answered you about the response. I don't think you can unmarshall it easily in the responseFilter. I've been debugging a bit and looking at the stack and I did not find an easy way. But, what info you need from the request? You could add a requestFilter and put information in the request context. You have available requestContext.setSecurityContext(...) but also requestContext.setProperty(...) – lrnzcig May 22 '14 at 14:59
  • There is some information in the request I want to send back to the user. But in the cases I need it, it's already in the response, so that works fine. Thanks again for your help. – nomve May 22 '14 at 20:24