Andreas Selenwall
Andreas Selenwall

Reputation: 5795

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.

Upvotes: 13

Views: 19519

Answers (3)

Rishabh
Rishabh

Reputation: 1

if you want your json as an Vote object then simple use @RequestBody Vote body in your mathod argument , Spring will automatically convert your Json in Vote Object.

Upvotes: -4

Naman
Naman

Reputation: 32036

@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));
}

Upvotes: 1

Lukasz Wiktor
Lukasz Wiktor

Reputation: 20422

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);
}

Upvotes: 23

Related Questions