jackson

Filter nested objects using Jackson's BeanPropertyFilter


I have the following objects:

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

}

I wrote a method to marshall a Person object like this:

@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));

}

What I'd like to see is JSON like this:

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

Is something like that possible?


Solution

  • 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" }))));