Can I specify the jackson @JsonView to use for method result transformation in RestEasy?

Viewed 2098

I'm working with a serialization model based on @JsonView. I normally configure jackson with a ContextResolver like this:

@Override
public ObjectMapper getContext(Class<?> aClass) {
    // enable a view by default, else Views are not processed
    Class view = Object.class;
    if (aClass.getPackage().getName().startsWith("my.company.entity")) {
        view = getViewNameForClass(aClass);
    }
    objectMapper.setSerializationConfig(
         objectMapper.getSerializationConfig().withView(view));
    return objectMapper;
}

This works fine if I serialize single entities. However, for certain use cases I want to serialize lists of my entities using the same view as for single entities. In this case, aClass is ArrayList, so the usual logic doesn't help much.

So I'm looking for a way to tell Jackson which view to use. Ideally, I'd write:

@GET @Produces("application/json; charset=UTF-8")
@JsonView(JSONEntity.class)
public List<T> getAll(@Context UriInfo uriInfo) {
    return getAll(uriInfo.getQueryParameters());
}

And have that serialized under the view JSONEntity. Is this possible with RestEasy? If not, how can I emulate that?

Edit: I know I can do the serialization myself:

public String getAll(@Context UriInfo info, @Context Providers factory) {
    List<T> entities = getAll(info.getQueryParameters());
    ObjectMapper mapper = factory.getContextResolver(
         ObjectMapper.class, MediaType.APPLICATION
    ).getContext(entityClass);
    return mapper.writeValueAsString(entities);
}

However, this is clumsy at best and defeats the whole idea of having the framework deal with this boilerplate.

1 Answers
Related