users@jersey.java.net

Re: [Jersey] GET method consuming JSON

From: Marc Hadley <marc.hadley_at_oracle.com>
Date: Fri, 9 Apr 2010 08:25:16 -0400

@Consumes only applies to the request message body so it isn't applicable to GET since that doesn't allow one. Example 1 looks right to me, to extract the JSON you would replace the "MyRequest myRequest" parameter in the action method with "@QueryParam("myRequest") SomeType myRequest".

SomeType can be any type that has a String constructor or a static valueOf or fromString method that takes a single String argument. See the javadoc for @QueryParam for full details.

Marc.

On Apr 9, 2010, at 6:11 AM, Franz Wong wrote:
>
> I would like to write a restful service which use @GET and @Consumes(MediaType.APPLICATION_JSON). I can only google example for @POST. I don't know whether I need to use @QueryParam for my parameters for GET method. If yes, how does the request line of the HTTP request become?
>
> Thanks.
> Franz
>
> (In real environment, the request line is url encodeded)
>
> 1. GET /myservice?myRequest={"actionList":["action1","action2"],"triggerName":"triggerName1"} HTTP/1.1
> 2. GET /myservice?{"myRequest":{"actionList":["action1","action2"],"triggerName":"triggerName1"}} HTTP/1.1
>
> Here is my code.
>
> @Singleton
> @Path("/")
> public class MyService {
> @Path("/myservice")
> // Use GET because jQuery.ajax sends OPTIONS instead of POST when using POST
> @GET
> @Consumes(MediaType.APPLICATION_JSON)
> @Produces(MediaType.APPLICATION_JSON)
> public MyResponse action(MyRequest myRequest) {
> return new MyResponse(); // currently no logic
> }
> }
>
> @XmlRootElement
> public class MyRequest {
> private List<String> actionList = new ArrayList<String>();
> private String triggerName;
>
> ... getters and setters
> }
>
> @XmlRootElement
> public class MyResponse {
> private String result;
>
> ... getters and setters
> }
>
> For reference, here is my client (in javascript) calling the service.
>
> $.ajax({
> type: "GET",
> url: "http://localhost:8080/myservice",
> dataType: "json",
> data: "{" +
> "\"myRequest\" : {" +
> "\"actionList\" : [\"action1\",\"action2\"]," +
> "\"triggerName\" : \"triggerName1\"" +
> "}" +
> "}",
> contentType: "application/json; charset=UTF-8",
> success: function(msg){
> alert("ok");
> },
> error: function(xhr, msg) { alert(msg + '\n' + xhr.responseText); }
> });