11

I have a requirement, where in i need to read JSON request that is coming in as part of the request and also convert it to POJO at the same time. I was able to convert it to POJO object. But I was not able to get the request body (payload) of the request.

For Ex: Rest Resource will be as follows

@Path("/portal")
public class WebContentRestResource {
    @POST
    @Path("/authenticate")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response doLogin(UserVO userVO) {
        // DO login
        // Return resposne
        return "DONE";
    }
}

POJO as

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class UserVO {
    @XmlElement(name = "name")
    private String username;

    @XmlElement(name = "pass")
    private String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}    

JSON Request is

{ 
  "name" : "name123",
  "pass" : "pass123"
}

Am able to get UserVO populated properly inside WebContentRestResource's doLogin() method. But i also need the Raw JSON that is submitted as part of the request.

Can any one help me?

Thanks ~Ashok

ashokr
  • 113
  • 1
  • 1
  • 7

2 Answers2

19

Here is an example for Jersey 2.0, just in case someone needs it (inspired by futuretelematics). It intercepts JSON and even allows to change it.

@Provider
public class MyFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext request) {
        if (isJson(request)) {
            try {
                String json = IOUtils.toString(req.getEntityStream(), Charsets.UTF_8);
                // do whatever you need with json

                // replace input stream for Jersey as we've already read it
                InputStream in = IOUtils.toInputStream(json);
                request.setEntityStream(in);

            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

    }

    boolean isJson(ContainerRequestContext request) {
        // define rules when to read body
        return request.getMediaType().toString().contains("application/json"); 
    }

}
acm
  • 1,616
  • 2
  • 12
  • 28
vladimir83
  • 479
  • 3
  • 9
  • In isJson() method must add check for (request.getMediaType() == null), in current edition it throws NullPointerException. – yurin Apr 04 '16 at 10:25
-2

One posibility is to use a ContainerRequestFilter that's called before your method is invoked:

public class MyRequestFilter 
  implements ContainerRequestFilter {
        @Override
    public ContainerRequest filter(ContainerRequest req) {
            // ... get the JSON payload here
            return req;
        }
}
futuretelematics
  • 1,328
  • 9
  • 23