users@jersey.java.net

Re: [Jersey] Set MediaType Programmatically

From: Craig McClanahan <Craig.McClanahan_at_Sun.COM>
Date: Thu, 13 Nov 2008 10:22:13 -0800

Jeremy Whitlock wrote:
> Hello All,
> As I typed the subject of this, I might had figured out a way to
> do this but basically, I want to have one method that returns multiple
> MediaTypes and the returned media type is dictated by a PathParam. Here
> is an example:
>
> @Path(/containers/list.{format})
> @Produces({"application/json", "application/xml"})
> public List<Container> getAllContainers(@PathParam("format") String
> format)
> {
> if (format.equals("json")
> // Set MediaType to JSON
> else
> // Set MediaType to XML
>
> return getContainersFromEM();
> }
>
> Here, getContainersFromEM() will return a List<Container> that will then
> get serialized to JSON or XML based on the format path param. This
> approach, at least from a url perspective, is similar to Twitters
> RESTful API:
> http://apiwiki.twitter.com/REST+API+Documentation#usertimeline. The
> idea behind something like this is to keep from having two different
> methods that differ only in content type. I've checked the samples but
> I'm pulling up blanks.
>
>
If you use Response.ResponseBuilder to create the response you can do
something like this:

    @Path(/containers/list.{format})
    @Produces({"application/json", "application/xml"})
    public Response getAllContainers(@PathParam("format") String format) {
        String type = format.equals("json") ? "application/json" :
"application/xml";
        return Response.ok(getContainersFromEM()).type(type).build();
    }

The "builder pattern" APIs (a method like type() that sets something on
the ResponseBuilder and returns a ResponseBuilder for continued
customization) makes it really easy to configure your response exactly
the way you would like it.

Craig

> Take care,
>
> Jeremy Whitlock | Software Engineer | CollabNet, Inc.
> 8000 Marina Blvd. Suite 600 | Brisbane, CA 94005 | USA
> O 650.228.2516 | C 970.988.8822 | jwhitlock_at_collab.net
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_jersey.dev.java.net
> For additional commands, e-mail: users-help_at_jersey.dev.java.net
>
>