简体   繁体   English

杰克逊将地图的子集序列化

[英]Jackson serialize a subset of a map

I have a map which I want to serialize using Jackson but only want to serialize a subset of it. 我有一个地图,我想使用Jackson进行序列化,但只想序列化它的一个子集。 Say I have a simple map as follows: 说我有一个简单的地图,如下所示:

final Map<String, String> map = new HashMap<>();
map.put("key 1", "value 1");
map.put("key 2", "value 2");
map.put("_internal key 1", "value 3");
map.put("_internal key 2", "value 4");

Then when serializing this I want to filter out any item whose key starts with _ , so that the serialized representation would be {'key 1': 'value 1','key 2': 'value 2'} . 然后,在对此进行序列化时,我想过滤掉键以_开头的所有项目,以便序列化的表示形式为{'key 1': 'value 1','key 2': 'value 2'}

I started looking at @JsonFilter but can't find any examples beyond very simplistic ones against basic types and nothing which appears to help with this more advanced type of filtering. 我开始研究@JsonFilter但是除了针对基本类型的非常简单的示例之外,找不到任何示例,并且似乎没有任何东西可以帮助这种更高级的过滤类型。

What's the best way to provide this custom serialization? 提供此自定义序列化的最佳方法是什么?

This is using Jackson 2.4, in case it matters. 以防万一,请使用Jackson 2.4。

You can achieve this by defining a Jackson filter which outputs the keys that don't start with an underscore, and enable this filter for all the Map classes via the annotation introspector . 您可以通过定义一个杰克逊(Jackson)过滤器来实现此目的,该过滤器输出不以下划线开头的键,并通过注释introspector对所有Map类启用此过滤器。 Here is an example: 这是一个例子:

public class JacksonMapSubset {

    public static void main(String[] args) throws JsonProcessingException {
        final Map<String, String> map = new HashMap<>();
        map.put("key 1", "value 1");
        map.put("key 2", "value 2");
        map.put("_internal key 1", "value 3");
        map.put("_internal key 2", "value 4");

        ObjectMapper mapper = new ObjectMapper();

        SimpleFilterProvider filters = new SimpleFilterProvider();
        final String filterName = "exclude-starting-with-underscore";
        mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
            @Override
            public Object findFilterId(Annotated a) {
                if (Map.class.isAssignableFrom(a.getRawType())) {
                    return filterName;
                }
                return super.findFilterId(a);
            }
        });
        filters.addFilter(filterName, new SimpleBeanPropertyFilter() {
            @Override
            protected boolean include(BeanPropertyWriter writer) {
                return true;
            }

            @Override
            protected boolean include(PropertyWriter writer) {
                return !writer.getName().startsWith("_");
            }
        });

        mapper.setFilters(filters);
        System.out.println(mapper.writeValueAsString(map));
    }
}

Output: 输出:

{"key 1":"value 1","key 2":"value 2"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM