gpt4 book ai didi

jackson - 使用 Jackson 的 BeanPropertyFilter 过滤嵌套对象

转载 作者:行者123 更新时间:2023-12-02 00:58:28 27 4
gpt4 key购买 nike

我有以下对象:

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

这样的事情可能吗?

最佳答案

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

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

关于jackson - 使用 Jackson 的 BeanPropertyFilter 过滤嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11036366/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com