Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the JSON body in Jersey?

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.

like image 323
Andreas Selenwall Avatar asked Dec 15 '16 06:12

Andreas Selenwall


2 Answers

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);
}
like image 112
Lukasz Wiktor Avatar answered Oct 18 '22 17:10

Lukasz Wiktor


@javax.ws.rs.Consumes(javax.ws.rs.core.MediaType.APPLICATION_JSON) 

should already help you here and just that the rest of the parameters must be marked using annotations for them being different types of params -

@POST()
@Path("/{itemId}")
@Consumes(MediaType.APPLICATION_JSON)
public void addVote(@PathParam("itemId") Integer itemId, <DataType> body) {
    voteDAO.create(new Vote(body));
}
like image 22
Naman Avatar answered Oct 18 '22 17:10

Naman