Vivek Singh Vivek Singh - 4 months ago 19
JSON Question

How to consume json parameter in java restful service

How can i consume json parameter in my webservice, I can able to get the parameters using @PathParam but to get the json data as parameter have no clue what to do.

@GET
@Path("/GetHrMsg/json_data")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces(MediaType.APPLICATION_JSON)
public String gethrmessage(@PathParam("emp_id") String empid) {


}

What to use in place of @PathParam and how to parse it later.

Answer

I assume that you are talking about consuming a JSON message body sent with the request.

If so, please note that while not forbidden outright, there is a general consensus that GET requests should not have request bodies. See the "HTTP GET with request body" question for explanations why.

I mention this only because your example shows a GET request. If you are doing a POST or PUT, keep on reading, but if you are really doing a GET request in your project, I recommend that you instead follow kondu's solution.


With that said, to consume a JSON or XML message body, include an (unannotated) method parameter that is itself a JAXB bean representing the message.

So, if your message body looks like this:

{"hello":"world","foo":"bar","count":123}

Then you will create a corresponding class that looks like this:

@XmlRootElement
public class RequestBody {
    @XmlElement String hello;
    @XmlElement String foo;
    @XmlElement Integer count;
}

And your service method would look like this:

@POST
@Path("/GetHrMsg/json_data")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void gethrmessage(RequestBody requestBody) {
    System.out.println(requestBody.hello);
    System.out.println(requestBody.foo);
    System.out.println(requestBody.count);
}

Which would output:

world
bar
123

For more information about using the different kinds of HTTP data using JAXB, I'd recommend you check out the question "How to access parameters in a RESTful POST method", which has some fantastic info.