简体   繁体   中英

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.

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

如果你想让你的json作为投票对象,那么在你的mathod参数中简单地使用@RequestBody Vote body,Spring将自动转换你的投票对象中的Json。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM