PlayFramework 2 with Jackson JsonViews annotation methods

I am trying to define some representations of an object in order to translate it into json in several ways. In Jax-rs, you can annotate the REST resource method also with @JsonView to indicate what kind you want in each resource. Is it possible to do something similar with controller methods in PlayFramework 2?

My essence:

public class User {
    public static class Normal{};
    public static class Complete extends Normal{};

    @Id
    @JsonView(Complete.class)
    private ObjectId id;
    @JsonView(Normal.class)
    @Property("user")
    private String username;
    @Property("pass")
    @JsonView(Normal.class)
    private String password;
    ...
}

And such a controller method:

@JsonView(User.Normal.class)
public static Result getUsers(){
    List<User> users = User.findAll();
    return ok(Json.toJson(users));
}

I want it to return only fields annotated with @JsonView (Normal.class), and obviously this does not work, it also returns an id field. Is it possible to get it without using ObjectMapper manually?

Thanks in advance!

+4
source share
1 answer

Try this ... it works for me.

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);

    try {
        String ret = mapper.writerWithView(User.Normal.class)
                .writeValueAsString(User.findAll());
+1

All Articles