users@jersey.java.net

Re: [Jersey] JSON + XML : how to choose the return type ?

From: Marc Hadley <Marc.Hadley_at_Sun.COM>
Date: Wed, 01 Apr 2009 14:40:05 -0400

On Apr 1, 2009, at 2:12 PM, Felipe Gaścho wrote:

> do you have a code snippet ?
>
Sure. Say you offer two media types like in your example below, in
your method you write something along the following lines:

@Path(...)
public ResourceClass {

   @Context Request request;

   @GET @Produces( { MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML })
   public someMethod() {
     List<Variant> availableVariants =
Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE,
       MediaType.APPLICATION_XML_TYPE).add().build();
     Variant bestMatch = request.selectVariant(availableVariants);
     MediaType bestMatchingType = bestMatch.getMediaType();
     return getSomeEntity(bestMatchingType);
   }
}

The call to selectVariant will have Jersey check the HTTP Accept
header for you and work out which of the media types you offer best
matches what the client requested.

Marc.


> On Wed, Apr 1, 2009 at 8:02 PM, Marc Hadley <Marc.Hadley_at_sun.com>
> wrote:
>> On Apr 1, 2009, at 12:07 PM, Felipe Gaścho wrote:
>>
>>> @Produces( { MediaType.APPLICATION_JSON,
>>> MediaType.APPLICATION_XML })
>>>
>>> I know the return type depends of some parameter in the request ..
>>> but
>>> which one ? how to choose between JSON and XML in runtime ?
>>>
>>> may I choose this through a browser url ? or I need to create a http
>>> request in other way ?
>>>
>> You can use Request.selectVariant at runtime to have the JAX-RS
>> impl select
>> the best matching representation from a set of available ones.
>>
>> https://jsr311.dev.java.net/nonav/releases/1.0/javax/ws/rs/core/Request.html
>> #selectVariant(java.util.List)
>>
>> Marc.
>>
>>
>>
>> ---------------------------------------------------------------------
>> To unsubscribe, e-mail: users-unsubscribe_at_jersey.dev.java.net
>> For additional commands, e-mail: users-help_at_jersey.dev.java.net
>>
>>
>
>
>
> --
>
> Please help to test this application:
> http://fgaucho.dyndns.org:8080/cejug-classifieds-richfaces
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_jersey.dev.java.net
> For additional commands, e-mail: users-help_at_jersey.dev.java.net
>