杰克逊默认包括所有公共吸气者。但是如果我有数百个吸气剂并且我想要序列化其中的几个,我怎么能实现这个目标呢?
我不想使用@JsonIgnore
注释来指定所有其他100个属性。
答案 0 :(得分:0)
您可以使用杰克逊的views或filters来选择对象的序列化形式。下面是一个使用过滤器的示例,它使用给定的名称来获取属性:
public class JacksonFilter {
@JsonFilter("filter")
public static class Bean {
private final String field1;
private final String field12;
private final String field10;
private final String field100;
public Bean(String field1, String field12, String field10, String field100) {
this.field1 = field1;
this.field12 = field12;
this.field10 = field10;
this.field100 = field100;
}
public String getField1() {
return field1;
}
public String getField12() {
return field12;
}
public String getField10() {
return field10;
}
public String getField100() {
return field100;
}
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
SimpleFilterProvider filters = new SimpleFilterProvider();
filters.addFilter("filter",
SimpleBeanPropertyFilter.serializeAllExcept("field12", "field100"));
mapper.setFilters(filters);
Bean bean = new Bean("A", "B", "C", "D");
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean));
}
}
输出:
{
"field1" : "A",
"field10" : "C"
}