Consuming JSON object in Jersey service

Viewed 65643

I've been Googling my butt off trying to find out how to do this: I have a Jersey REST service. The request that invokes the REST service contains a JSON object. My question is, from the Jersey POST method implementation, how can I get access to the JSON that is in the body of the HTTP request?

Any tips, tricks, pointers to sample code would be greatly appreciated.

Thanks...

--Steve

7 Answers

Some of the answers say a service function must use consumes=text/plain but my Jersey version is fine with application/json type. Jackson and Jersey version is jackson-core=2.6.1, jersey-common=2.21.0.

@POST
@Path("/{name}/update/{code}")
@Consumes({ "application/json;charset=UTF-8" })
@Produces({ "application/json;charset=UTF-8" })
public Response doUpdate(@Context HttpServletRequest req, @PathParam("name") String name, 
      @PathParam("code") String code, String reqBody) {
  System.out.println(reqBody);

  StreamingOutput stream = new StreamingOutput() {
    @Override public void write(OutputStream os) throws IOException, WebApplicationException {
      ..my fanzy custom json stream writer..
    }
  };

  CacheControl cc = new CacheControl();
  cc.setNoCache(true);
  return Response.ok().type("application/json;charset=UTF-8")
    .cacheControl(cc).entity(stream).build();
}

Client submits application/json request with a json request body. Servlet code may parse string to JSON object or save as-is to a database.

SIMPLE SOLUTION:

If you just have a simple JSON object coming to the server and you DON'T want to create a new POJO (java class) then just do this.

The JSON I am sending to the server

{
    "studentId" : 1
}

The server code:

    //just to show you the full name of JsonObject class
    import javax.json.JsonObject; 

    @Path("/")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response deleteStudent(JsonObject json) {
        //Get studentId from body <-------- The relevant part 
        int studentId = json.getInt("studentId");
        
        //Return something if necessery
        return Response.ok().build();
    }
Related