How to include only specific properties when serializing with Jackson

前端 未结 3 1770
猫巷女王i
猫巷女王i 2021-01-05 10:21

I am trying to implement a universal method which serializes the given object to JSON, but only those properties which are passed in a collection. If possible I want to get

3条回答
  •  灰色年华
    2021-01-05 11:10

    Based on http://www.cowtowncoder.com/blog/archives/2011/09/entry_461.html an alternate way to set up the filter is setting up a class that extends JacksonAnnotationIntrospector and overrides findFilterId. You can then specify to find your filter in the findFilterId. This could be made to be as robust if you want based on some other map or algorithm. Below is sample code. Not sure if the performance is better than the solution above but it seems to be simpler and probably more easily extensible. I was doing this for serializing CSV using Jackson. Any feedback is welcome!

    public class JSON {
    
    private static String FILTER_NAME = "fieldFilter";
    
    public static String serializeOnlyGivenFields(Object o,
                                                  Collection fields) throws JsonProcessingException {
        if ((fields == null) || fields.isEmpty()) fields = new HashSet();
    
        Set properties = new HashSet(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;
        }
    }
    
    }
    

提交回复
热议问题