users@jersey.java.net

Set MediaType Programmatically

From: Jeremy Whitlock <jwhitlock_at_collab.net>
Date: Thu, 13 Nov 2008 09:56:56 -0800

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.

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