How to read JSON request body in jersey

I have a requirement when I need to read a JSON request, which is included as part of the request, and also convert it to POJO at the same time. I was able to convert it to a POJO object. But I could not get the request body (payload) of the request.

For example: The Res 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 how

 @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

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

I can configure UserVO correctly in the doLogin () method of WebContentRestResource. But I also need Raw JSON, which is sent as part of the request.

Can anyone help me?

Thanks ~ Ashok

+8
jersey jersey-client
source share
2 answers

Here is an example for Jersey 2.0, in case someone needs it (inspired by future math). It intercepts JSON and even allows you 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"); } } 
+7
source share

One possibility is to use the ContainerRequestFilter , which is called before , your method is called:

 public class MyRequestFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest req) { // ... get the JSON payload here return req; } } 
-2
source share

All Articles