Vivek Singh Vivek Singh - 1 year ago 64
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.

@Consumes({ 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 Source

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:


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

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

And your service method would look like this:

public void gethrmessage(RequestBody requestBody) {

Which would output:


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.