How do I get the JSON body in Jersey?

Andreas Selenwall picture Andreas Selenwall · Dec 15, 2016 · Viewed 12.2k times · Source

Is there a @RequestBody equivalent in Jersey?

@POST()
@Path("/{itemId}")
@Consumes(MediaType.APPLICATION_JSON)
public void addVote(@PathParam("itemId") Integer itemId, @RequestBody body) {
    voteDAO.create(new Vote(body));
}

I want to be able to fetch the POSTed JSON somehow.

Answer

Lukasz Wiktor picture Lukasz Wiktor · Dec 15, 2016

You don't need any annotation. The only parameter without annotation will be a container for request body:

@POST()
@Path("/{itemId}")
@Consumes(MediaType.APPLICATION_JSON)
public void addVote(@PathParam("itemId") Integer itemId, String body) {
    voteDAO.create(new Vote(body));
}

or you can get the body already parsed into object:

@POST()
@Path("/{itemId}")
@Consumes(MediaType.APPLICATION_JSON)
public void addVote(@PathParam("itemId") Integer itemId, Vote vote) {
    voteDAO.create(vote);
}