杰克逊:有两个不同的阶级表示

时间:2016-08-01 12:09:51

标签: java json jackson

我有一个简单的用户类:

public class User {
    private long id;
    private String username;
    private String password;
    private String someCommonData;
    private String someAdminData;
}

我想在json中对该用户进行不同的表示。 普通用户的版本:

{"username":"myName", "someCommonData":"bla"}

和adminUsers的代表:

{"id":1, "username":"myName", "someCommonData":"bla", "someAdminData":"don't show this to the user!"}

当我使用 @JsonIgnore 时,它总是被忽略,但我希望有条件忽略。

到目前为止唯一可行的解​​决方案是拥有两个不同的类。难道没有一个更美丽的解决方案吗?

2 个答案:

答案 0 :(得分:1)

查看@JsonView

public class User {
    @JsonView({Admin.class})
    private long id;

    @JsonView({Basic.class})
    private String username;

    @JsonIgnore
    private String password;

    @JsonView({Basic.class})
    private String someCommonData;

    @JsonView({Admin.class})
    private String someAdminData;

    static class Basic {
    }

    static class Admin extends Basic {
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();


        User user = new User();
        user.id = 1L;
        user.username = "admin";
        user.password = "nimda";
        user.someCommonData = "common-data";
        user.someAdminData = "admin-data";

        ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();

        System.out.println(writer.withView(Basic.class).writeValueAsString(user));
        System.out.println(writer.withView(Admin.class).writeValueAsString(user));
    }
}

主要输出:

{
  "username" : "admin",
  "someCommonData" : "common-data"
}
{
  "id" : 1,
  "username" : "admin",
  "someCommonData" : "common-data",
  "someAdminData" : "admin-data"
}

此博客介绍了基础知识:http://www.baeldung.com/jackson-json-view-annotation

答案 1 :(得分:0)

我能想到的最好和最容易的方法是使用两个分类。抱歉。 但是当你这样做时,它看起来像是一个更好的设计:

public class User {
    private long id;
    private String username;
    private String password;
    private String someCommonData;
}

public class Admin extends User {
    private String someAdminData;
}