users@jersey.java.net

[Jersey] Multiple Jackson ObjectMapper and Mixins

From: Eduardo Sherington <eduardosherington_at_hotmail.com>
Date: Tue, 15 Jan 2013 20:34:11 +0000

Hello,

I am using the latest Jersey 2.0 milestone quite successfully in a standalone server application (no servlet container). I deal only in JSON and I have all of the basics working.

I have code similar to the following pseudo code, it's a contrived example but it is very similar to my use-case:

class Movie {

    String title; // Summary info
    int year; // Summary info

    List<Person> cast; // Detail info
    List<Person> crew; // Detail info
}

class Movies {
    // just a wrapper around a List<Movie>
}

@Path("movies")
class MovieResource {

    @GET
    @Produces("application/json")
    public Movies getMovies() {
        // Return all movies, including cast and crew
    }
}

@Path("search/movies")
class SearchResource {

    @GET
    @Produces("application/json")
    public Movies findAllMovies() {
        // Return all movies, but only summary information, not including cast and crew
    }

}

What I am trying to do is to use the same Movie domain object for both services, but in the case of the SearchResource I only want the summary fields returned via the web service and not the detail fields (the cast and crew).

So what I wanted to do was to use different Jackson ObjectMapper instances each with different Jackson "mixins" to tailor the JSON returned by each web service. In practical terms MovieResource uses an ObjectMapper that serializes the whole object, but SearchResource uses a different ObjectMapper with a mixin to "@JsonIgnore" the cast and crew properties. This is all working in a unit-test.

I know how I can use my own ObjectMapper instead of the default one, but that would be for *all* requests and that's not what I want.

So my question is: is what I am trying to do possible in Jersey 2.0, and if so how?

Of course I could use different domain objects (maybe a Movie and a MovieSummary with a sub-set of the fields) to implement this differently but that feels like unnecessary duplication - hence my question.

Thanks!