dev@glassfish.java.net

Re: How to POST a list of strings ?

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Thu, 13 Nov 2008 11:12:53 +0100

Hi Farjola,


On Nov 13, 2008, at 10:30 AM, Farjola Zaloshnja wrote:

> Hi,
> I haven't used much the POST function in the jsr311 framework but if
> I were to post a list of strings will this be correct?
>

Do you want to encode a list of strings as a JSON array? for example:

   ["foo", "bar", "baz"]

If so you can utilize the Jettison [1] class
org.codehaus.jettison.json.JSONArray class [2].

 From the client:

   Client c = Client.create();
   WebResource r = c.resource("http://host/path");

   JSONArray ja = new JSONArray(Arrays.asList("foo", "bar"));
   r.type("application/json").post(ja);

With a resource class with the following resource method:

    @Path("path")
    @POST
    @Consumes("application/json");
    public void post(JSONArray ja) {
      ...
    }

The reason List<String> does not work as you expect is that Jersey
does not know how to serialize List<String> in the JSON format. If you
want to support that you can add your own functionality utilizing
MessageBodyWriter. See the following sample for more details:

   http://download.java.net/maven/2/com/sun/jersey/samples/entity-provider/1.0/entity-provider-1.0-project.zip

Paul.

[1] http://jettison.codehaus.org/
[2] http://www.json.org/javadoc/org/json/JSONArray.html
      Note that Jettison copies the classes from JSON.org do the
JavaDoc should still apply.

>
> On the client side:
>
> Client c = Client.create();
>
> URI url =
>
> new URI("getmylist");
> ClientRequest cr = ClientRequest.create().entity(List<String> mylist,
>
> "application/json").build(url, "POST");
> And the server side receiving will look like:
>
>
> @POST
>
> @Path("getmylist")
>
> public void getmylist(List<String> programids){ }
>
> Any comments ?
>
> Thank you,
>
> Farjola
>
>
>
>