users@jersey.java.net

Re: [Jersey] Does Jersey understand generics marshalling/unmarshalling ??

From: Paul Sandoz <Paul.Sandoz_at_oracle.com>
Date: Fri, 13 Aug 2010 13:18:02 +0200

Hi Isaac,

The default support for JSON uses integration with JAXB and JAXB does
support this general type of wrapping concept out of the box. It needs
to know statically the stuff it needs to marshall/unmarshall.

It is possible to define your own message body readers/writers that
supports such wrapping and can defer to other message body readers/
writers for the wrapped type. Such readers/writers have access to the
parameterized Type.

And, it is also possible to use Jackson with Jersey. So i suspect if
you can use Jackson to support your requirements you can plug it into
Jersey.

Paul.

On Aug 12, 2010, at 9:50 PM, Isaac Voth wrote:

> The JSON format we want to work with uses a standard wrapper around
> business objects or lists of business objects. So things look like
> this:
>
> { "version" : "1.0" , "data" : {
> "name" : "frank" , "age" : 30
> } }
>
> Or
>
> { "version" : "1.0" , "data" : {
> "make" : "BMW" , "color" : "yellow", "size" : "535", "price" : 500000
> } }
>
> The object inside the data tag, I want to marshall into an object of
> varying types, depending on the REST method called. So in some cases
> it might be a person (with a name and age) and in others a car. So
> from a java perspective a Wrapper<Person> or Wrapper<Car>. Or
> sometimes Wrapper<List<Car>>.
>
> The Java code would look something like this:
>
> @POST
> @Consumes("application/json")
> @Produces("application/json")
> public Wrapper<Person> updatePerson(Wrapper<Person> personWrapper) {
> ....
> }
>
> @POST
> @Consumes("application/json")
> @Produces("application/json")
> public Wrapper<Car> updatePerson(Wrapper<Car> carWrapper) {
> ....
> }
>
>
> Is it simply the case that Jersey can not read the generics because
> they are a compile time thing?
>
> Is it possible to do something like this without needing to create a
> custom wrapper for each contained object, basically forget about
> generics and hard code the type for "data"? This is what we are
> doing right now, but it is less than elegant. There is a CarWrapper
> and a Car bean, and also a CarListWrapper.
>
> I am considering scrapping Jersey and going with a Servlet + Jackson
> solution. With this I can use a type definition object (like
> GenericEntity) that is basically an empty instantiation that
> represents the type - sort of a runtime generics hack. But I would
> really like to use Jersey because the REST annotations are beautiful.
>
> Thanks - any and all suggestions welcome.
>
> isaac