【发布时间】:2014-11-27 20:46:46
【问题描述】:
假设我有两个简单的类
@JsonFilter("filter properties by name")
public class Foo
{
private Integer id;
private String name;
}
@JsonFilter("filter properties by name")
public class Bar
{
private Integer id;
private String name;
private Foo foo;
}
我想序列化Bar 的一个实例,其中foo 字段只有它的ID。这一切都应该在运行时完成。
我尝试使用过滤器来做到这一点
FilterProvider filter = new SimpleFilterProvider().addFilter(
"filter properties by name", SimpleBeanPropertyFilter
.serializeAllExcept(/*name of the field to exclude*/));
objectMapper.writer(filter).writeValuAsString(bar);
但是,这样做时,我必须手动排除父类的所有字段;此外,如果此字段之一与子类的字段名称相同,则它们都被排除在外。
在我的示例中,我不能以这种方式排除字段 name,因为它也会影响 Bar 类的字段 name。
那么,我怎样才能以最简洁/优雅的方式解决? 有没有类似于上面的代码,可能使用点符号或类似的东西?
例如到现在为止,在我的示例过滤器中,我可以写类似[...].serializeAllExcept("name", "foo")); 的东西,但是拥有[...].serializeAllExcept("foo.name")); 或类似的东西真是太好了。
【问题讨论】: