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

Question

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.


Show source
| java   | rest   | json   | jax-rs   | put   2016-12-08 14:12 1 Answers

Answers to How to retrieve the JSON message body in JAX-RS REST method? ( 1 )

  1. 2016-12-08 15:12

    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

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

◀ Go back