users@jersey.java.net

Re: [Jersey] Omitting fields on some requests

From: Tatu Saloranta <tsaloranta_at_gmail.com>
Date: Mon, 21 Jun 2010 15:16:02 -0700

On Mon, Jun 21, 2010 at 2:36 PM, Mike Boyers <mboyers_at_yahoo.com> wrote:
> Using Jersey, I'm producing a JSON response that's an array of objects.  The object in question has about 25 fields.
>
> There are some cases where I want to return an array of these objects and include every one of the object's fields in the response.
>
> However, there are also cases where I'd like to produce an abbreviated response that only contains a subset of the fields from the object.
>
> I'm trying to find a way to do this without having to make a different POJO for the abbreviated response.
>
> The only thing I've found so far is the @XmlTransient annotation, which is sort of along the same lines of what I'm looking for, but I'm looking for a way to do it conditionally.

If you are using Jackson-based JSON provider, you could do this with
JSON Views (http://wiki.fasterxml.com/JacksonJsonViews). It's an
annotation-based way to indicate different views (profiles).
But since Jersey knows nothing about views, you might be better off
calling Jackson's ObjectMapper directly to produce output; I usually
use StreamingOutput as wrapper to achieve this.

Alternatively with JAXB what you could do is to define an interface
with only those getters and setters that are applicable to subset, and
make real object implement this interface. You would then need to
convince JAXB serializer that type you want is that of this interface,
similar to how you would work with Jackson-based serializer.

-+ Tatu +-