users@jersey.java.net

Re: [Jersey] JSON as method arguments

From: Jakub Podlesak <Jakub.Podlesak_at_Sun.COM>
Date: Wed, 16 Dec 2009 15:39:44 +0100

On Tue, Dec 15, 2009 at 04:29:44PM -0500, jmrodri_at_gmail.com wrote:
> I'm having a bit of a problem trying to POST JSON to a method with 2 or
> more arguments.

For a String parameter and JSON data, if you can change the JSON data
format, i would suggest to include the String value into the JSON data
(st. like: { "origString":"the string val","origJson":{...}})
and send just that. If you still need to send both separately,
then as the HTTP request has only one body, you would need to use
either the form data, as you mentioned, or some other way to fit
multilple entities in. Another option would be then the multipart/mixed
approach. Please see [1] for details.

HTH,

~Jakub

[1]https://jersey.dev.java.net/nonav/apidocs/latest/contribs/jersey-multipart/index.html
>
> For example, I have a create(ConsumerInfo ci, String label) method in a
> ConsumerResource
> class.
>
> @POST
> @Consumes({MediaType.APPLICATION_JSON,
> MediaType.APPLICATION_FORM_URLENCODED})
> @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
> public Consumer create(ConsumerInfo ci, String label) ...
>
> If I remove the label param, I am able to easily POST a JSON object and
> have it converted to a
> ConsumerInfo quite easily. But once I add a second parameter, it always
> gets the value of null.
>
> My client is a python script, though I've tried using the jersey java
> client as well. With the jersey
> client, I'm not sure how to pass in multiple objects to the post() method
>
> WebResource postresource =
> c.resource("http://localhost:8080/candlepin/test/");
> postresource.accept("application/json").type("application/json").post(ci);
>
> ci is my ConsumerInfo object, but looking at the javadoc for post() it
> always takes in either one
> object, or one object and a return class type. How would I pass in the
> String?
>
> From python, it's a similar problem but I'm not dealing with objects, more
> straight json.
> So once I know what the json needs to look like, I can figure that part out.
>
> Would I be able to pass in a List of parameters? For example,
>
> List<Object> params = new ArraysList<Object>();
> params.add(ci); // add my ConsumerInfo
> params.add("new-consumer");
> postresource.accept("application/json").type("application/json").post(params);
>
> Anyone done something like this? The only other way I know how to do this
> is to get
> rid of the POST of JSON and stick with APPLICATION_FORM_URLENCODED, but that
> then leads me to how will this work with PUT then.
>
> Thoughts? Advice?
>
> Sincerely,
> jesus



-- 
http://blogs.sun.com/japod