Play Framework 2采用Jackson Json Views注释方法

时间:2013-10-29 09:56:34

标签: playframework-2.0 jackson

我正在尝试定义一些实体的视图,以某种不同的方式将其转换为json。在Jax-rs中,也可以使用@JsonView来注释REST资源方法,以指定每个资源中需要哪个视图。是否可以在PlayFramework 2中使用Controller方法执行类似操作?

我的实体:

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;
    ...
}

这样的Controller方法:

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

我希望它只返回用@JsonView(Normal.class)注释的字段,显然这不起作用,它还返回id字段。是否可以在不必手动使用ObjectMapper的情况下获取它?

提前致谢!

1 个答案:

答案 0 :(得分:1)

试试这个...它对我有用。

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

    try {
        String ret = mapper.writerWithView(User.Normal.class)
                .writeValueAsString(User.findAll());
相关问题