Filter nested objects using Jackson's BeanPropertyFilter

前端 未结 2 895
灰色年华
灰色年华 2021-01-11 20:29

I have the following objects:

@JsonFilter(\"myFilter\")
public class Person {
    private Name name;
    private int age;
    public Name getName() {return n         


        
相关标签:
2条回答
  • 2021-01-11 21:12

    There's a better way that solves problem with property name conflicts. Just add another filter to class Name ("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;}
    }
    

    And then add 2 filters, one for Person and one for Name:

    FilterProvider filterProvider = new SimpleFilterProvider()
                .addFilter("personFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"))
                .addFilter("nameFilter", SimpleBeanPropertyFilter.filterOutAllExcept("firstName"));
    
    0 讨论(0)
  • 2021-01-11 21:14

    Ok, figured it out. Varargs would have made this a bit prettier, but oh well. Just hope I don't have two inner beans which have properties with the same name. I wouldn't be able to make the distinction between the two

        FilterProvider filters = new SimpleFilterProvider()
                .addFilter("myFilter", SimpleBeanPropertyFilter
                        .filterOutAllExcept(new HashSet<String>(Arrays
                                .asList(new String[] { "name", "firstName" }))));
    
    0 讨论(0)
提交回复
热议问题