如何在JAX-RS REST方法中检索JSON消息正文? [英] How to retrieve the JSON message body in JAX-RS REST method?
问题描述
我在邮件正文中有以下JSON
,它们将作为HTTP请求的一部分传递.
I have the following JSON
that will be passed as part of a HTTP request, in the message body.
{
"names": [
{
"id":"<number>",
"name":"<string>",
"type":"<string>",
}
]
}
我当前的REST
处理程序如下.我可以获取作为路径参数传递的ID和版本,但是我不确定如何在邮件正文中检索内容?
My current REST
handler is below. I am able to get the Id and `Version that is passed in as path params, but I am not sure how to retrieve the contents on the message body?
@PUT
@Path("/Id/{Id}/version/{version}/addPerson")
public Response addPerson(@PathParam("Id") String Id,
@PathParam("version") String version) {
if (isNull(Id) || isEmpty(version)) {
return ResponseBuilder.badRequest().build();
}
//HOW TO RECIEVE MESSAGE BODY?
//carry out PUT request and return DTO: code not shown to keep example simple
if (dto.isSuccess()) {
return Response.ok().build();
} else {
return Response.serverError().build();
}
}
注意:我正在使用JAX-RS
框架.
Note: I am using the JAX-RS
framework.
推荐答案
您只需要将名称json映射到POJO并将@Consumes批注添加到put方法中,下面是一个示例:
You just need to map your name json to a POJO and add @Consumes annotation to your put method, here is an example:
@PUT
@Consumes("application/json")
@Path("/Id/{Id}/version/{version}/addPerson")
public Response addPerson(@PathParam("Id") String Id,
@PathParam("version") String version,
List<NamObj> names) {
如果不是这种情况,我假设您正在尝试检索元素列表,只需在参数中使用POJO即可.
I assume you are trying to retrieve a list of elements if is not the case just use you POJO as it in the param.
根据您在服务器中使用的json库,您可能需要在POJO中添加@xml批注,以便解析器知道如何映射请求,这就是示例json的映射应如下所示:
Depending on what json library are you using in your server you may need to add @xml annotation to your POJO so the parser could know how to map the request, this is how the mapping for the example json should look like:
@XmlRootElement
public class NameObj {
@XmlElement public int id;
@XmlElement public String name;
@XmlElement public String type;
}
Jersey文档: https://jersey.java.net/documentation/latest/user-guide.html#json
Jersey doc: https://jersey.java.net/documentation/latest/user-guide.html#json
@化妆品参考: http://docs.oracle .com/javaee/6/tutorial/doc/gilik.html#gipyt
这篇关于如何在JAX-RS REST方法中检索JSON消息正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!