users@jersey.java.net

Modifying JAXB Behavior for Returned Objects

From: Tim McNerney <java_at_oneofus.org>
Date: Fri, 16 Oct 2009 15:27:32 -0700

I'm using JAXB notation on a simple bean as a return value for some @GET
methods, converted to either JSON or XML. In one case, I am return a single
instance, but in another, I return a list of items. For the single object,
I'd like to convert to the complete value, but when returning a list, I'd
like an abbreviated representation. Is there any declarative way to do this?
Otherwise a clean programmatic method?
As an example, let's say I have:

@XmlRootElement
public class Article {
    public String getTitle() {
        return this.title;
    }

    public String getAbstract() {
        return this.abstract;
    }

    public String getBody() {
        return this.body;
    }
}

@Path("/article/")
public class ArticleResource {
    @GET
    @Produces({"application/xml", "application/json"})
    public List<Article> getList() {
    }

    @GET
    @Path("{articleId}/")
    @Produces({"application/xml", "application/json"})
    public List<Article> getArticle(@PathParam("articleId") Integer
articleId) {
    }
}

In the case of getList(), I'd like the conversion to JSON/XML to only
include the Title and Abstract, but when I return a single entry, I'd like
to return the Body as well. Is there some way to indicate that getBody is an
XmlTransient in the case of the getList call, but not for getArticle? Or
some other trick to indicate the different behavior?

Thanks.

--Tim