我正在尝试实现一种通用方法,它将给定的对象序列化为 JSON,但仅限于在集合中传递的那些属性。如果可能的话,我想获得此功能而不在类上指定 @JsonFilter
。为此,我尝试使用 FilterExceptFilter
来自 jackson 2.4.1。依赖关系:
这是我现在所拥有的:
public static String serializeOnlyGivenFields(Object o,
Collection<String> fields) throws JsonProcessingException {
if ((fields == null) || fields.isEmpty()) return null;
Set<String> properties = new HashSet<String>(fields);
SimpleBeanPropertyFilter filter =
new SimpleBeanPropertyFilter.FilterExceptFilter(properties);
SimpleFilterProvider fProvider = new SimpleFilterProvider();
fProvider.addFilter("fieldFilter", filter);
fProvider.setDefaultFilter(filter);
ObjectMapper mapper = new ObjectMapper();
mapper.setFilters(fProvider);
String json = mapper.writeValueAsString(o);
return json;
}
但是,过滤器从未应用。它始终序列化所有属性。
Set<String> fields = new HashSet<String>(); fields.add("name");
String json = Serializer.serializeOnlyGivenFields(e, fields);
System.out.println(json);
{"name":"Test entity","description":"Test description"}
我还尝试注册 FilterProvider
on the ObjectWriter
,但结果相同:
String json = mapper.writer(fProvider).writeValueAsString(o);
我错过了什么? jackson 有什么好方法可以实现这一目标吗?
最佳答案
基于http://www.cowtowncoder.com/blog/archives/2011/09/entry_461.html设置过滤器的另一种方法是设置一个扩展 JacksonAnnotationIntrospector 并覆盖 findFilterId 的类。然后,您可以指定在 findFilterId 中查找您的过滤器。如果您想要基于其他 map 或算法,这可以变得同样强大。下面是示例代码。不确定性能是否比上面的解决方案更好,但它似乎更简单并且可能更容易扩展。我这样做是为了使用 Jackson 序列化 CSV。欢迎任何反馈!
public class JSON {
private static String FILTER_NAME = "fieldFilter";
public static String serializeOnlyGivenFields(Object o,
Collection<String> fields) throws JsonProcessingException {
if ((fields == null) || fields.isEmpty()) fields = new HashSet<String>();
Set<String> properties = new HashSet<String>(fields);
SimpleBeanPropertyFilter filter =
new SimpleBeanPropertyFilter.FilterExceptFilter(properties);
SimpleFilterProvider fProvider = new SimpleFilterProvider();
fProvider.addFilter(FILTER_NAME, filter);
ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector( new AnnotationIntrospector() );
String json = mapper.writer(fProvider).writeValueAsString(o);
return json;
}
private static class AnnotationIntrospector extends JacksonAnnotationIntrospector {
@Override
public Object findFilterId(Annotated a) {
return FILTER_NAME;
}
}
}
关于json - 使用 Jackson 进行序列化时如何仅包含特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26509033/