1

I have been through this link. but this did not helped me out.

I am using jersey lib v1.17.1. My jersey rest service:

@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@Path("/post1")
public ResponseBean post1(@QueryParam("param1")String param1)
{
    return ResponseFactory.createResponse(param1, "TEST", "TEST", null, true);
}

url is: /test/post1

My ajax call:

var d = {"param1":"just a dummy data"};
    $.ajax({
        type : "POST",
        url : "http://localhost:7070/scl/rs/test/post1",
        contentType :"application/json; charSet=UTF-8",
        data : d,
        dataType : "json"
    })
    .done(function(data){
        console.log(data);
    })
    .fail(function(data){
        console.log(data);
    });

It hits to my rest service but as param1 I am alway getting null value. The alternate solution is to add JavaBean with @XMLRootElement which will marshal/unmarshal the java object to json and vice versa, but I do not want to use this.
Is there any way to post data and receive it using appropriate annotation like @QueryParam or something like that ? Please help

Community
  • 1
  • 1
user3137239
  • 149
  • 2
  • 3
  • 9

3 Answers3

4

Your server-side code should be like this:

@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@Path("/post1")
public ResponseBean post1(Data param1)
{
    return ResponseFactory.createResponse(param1, "TEST", "TEST", null, true);
}

where Data is a (POJO) class annotated with @XmlRootElement and corresponds to the JSON data what your client will send (ie, have a param1 field with getter and setter). The JAX-RS implementation will unmarshall the body of the POST into an instance of Data.

@QueryParam annotation is used ot retrieve the query params in a (usually) GET requests. Query params are the params after the question mark (?). Eg: @QueryParam("start") String start will map be set to 1 when the following request is processed: GET http://foo.com/bar?start=1, but this is not what you're doing in your case, AFAICS.

Xavier Coulon
  • 1,530
  • 9
  • 14
1
You can simply take Post dat as a string and then you can parse it using JSONObject.
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@Path("/post1")
    public Response postStrMsg(String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }
Pinkesh Sharma
  • 2,138
  • 16
  • 15
0

the @XMLRootElement is the way to do that since the json must be unmarshaled before you can use any of its elements.

Vasile
  • 134
  • 2