Filter nested objects using Jackson 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 sort the Person object as follows:

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

I would like to see JSON as follows:

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

Is something like this possible?

+4
source share
2 answers

Ok, got it. Vargard would have made it a little prettier, but good. I hope I do not have two internal beans that have properties with the same name. I could not distinguish between the two

  FilterProvider filters = new SimpleFilterProvider() .addFilter("myFilter", SimpleBeanPropertyFilter .filterOutAllExcept(new HashSet<String>(Arrays .asList(new String[] { "name", "firstName" })))); 
+5
source

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

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")); 
+1
source

All Articles