How to retrieve the JSON message body in JAX-RS REST method?

回眸只為那壹抹淺笑 提交于 2019-12-07 23:53:04

问题


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>",
        }
    ]
}

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

}

Note: I am using the JAX-RS framework.


回答1:


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) {

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.

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 doc: https://jersey.java.net/documentation/latest/user-guide.html#json

@cosumes reference: http://docs.oracle.com/javaee/6/tutorial/doc/gilik.html#gipyt



来源:https://stackoverflow.com/questions/41041160/how-to-retrieve-the-json-message-body-in-jax-rs-rest-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!