How do I get the JSON body in Jersey?

2020-04-04 12:59发布

问题:

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.

回答1:

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


回答2:

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


回答3:

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.