10

我有以下对象:

@JsonFilter("myFilter")
public class Person {
    private Name name;
    private int age;
    public Name getName() {return name;}
    public void setName(Name name) {this.name = name;}
    public int getAge() {return age;}
    public void setAge(int age) {this.age = age;}
}

@JsonFilter("myFilter")
public class Name {
    private String firstName;
    private String lastName;
    public String getFirstName() {return firstName;}
    public void setFirstName(String firstName) {this.firstName = firstName;}
    public String getLastName() {return lastName;}
    public void setLastName(String lastName) {this.lastName = lastName;}

}

我写了一个方法来编组这样的 Person 对象:

@Test
public void test() throws Exception {

    Person person = new Person();
    person.setAge(10);
    Name name = new Name();
    name.setFirstName("fname");
    name.setLastName("lastname");
    person.setName(name);

    ObjectMapper mapper = new ObjectMapper();

    FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter",
            SimpleBeanPropertyFilter.filterOutAllExcept("name.firstName"));

    System.out.println(mapper.filteredWriter(filters).writeValueAsString(person));

}

我希望看到的是这样的 JSON:

{"name":{"firstName":"fname"}}

这样的事情可能吗?

4

2 回答 2

7

好的,想通了。Varargs 会让这更漂亮一点,但是哦,好吧。只是希望我没有两个具有相同名称的属性的内部 bean。我将无法区分两者

    FilterProvider filters = new SimpleFilterProvider()
            .addFilter("myFilter", SimpleBeanPropertyFilter
                    .filterOutAllExcept(new HashSet<String>(Arrays
                            .asList(new String[] { "name", "firstName" }))));
于 2012-06-14T18:20:01.580 回答
6

有一种更好的方法可以解决属性名称冲突的问题。只需将另一个过滤器添加到类名称(“nameFilter”):

@JsonFilter("personFilter")
public class Person {
    private Name name;
    private int age;
    public Name getName() {return name;}
    public void setName(Name name) {this.name = name;}
    public int getAge() {return age;}
    public void setAge(int age) {this.age = age;}
}

@JsonFilter("nameFilter")
public class Name {
    private String firstName;
    private String lastName;
    public String getFirstName() {return firstName;}
    public void setFirstName(String firstName) {this.firstName = firstName;}
    public String getLastName() {return lastName;}
    public void setLastName(String lastName) {this.lastName = lastName;}
}

然后添加 2 个过滤器,一个用于 Person,一个用于 Name:

FilterProvider filterProvider = new SimpleFilterProvider()
            .addFilter("personFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"))
            .addFilter("nameFilter", SimpleBeanPropertyFilter.filterOutAllExcept("firstName"));
于 2016-06-16T12:32:18.840 回答