Question

I have a bean which contains a lot Boolean fields. I only want to add those fields with true values to json to save some payload. This is a feature and should be based on client's demand so it has to be done in a dynamic way. I don't think annotations will work because they are static things. Any idea on this?

Was it helpful?

Solution

In addition to the Jackson's views you can write a custom Jackson filter which would filter out the negative values of all the boolean fields.

Here is an example:

public class JacksonFilterBoolean {
    @JsonFilter("boolean-filter")
    public static class Test {
        public final Boolean f1;
        public final boolean f2;
        public final boolean f3;
        public final Boolean fNull = null;
        public final String f4 = "string";

        public Test(Boolean f1, boolean f2, boolean f3) {
            this.f1 = f1;
            this.f2 = f2;
            this.f3 = f3;
        }
    }

    public static class BooleanPropertyFilter extends SimpleBeanPropertyFilter {
        @Override
        protected boolean include(BeanPropertyWriter writer) {
            return true;
        }

        @Override
        protected boolean include(PropertyWriter writer) {
            return true;
        }

        @Override
        public void serializeAsField(Object pojo, JsonGenerator jgen,
                                     SerializerProvider provider, PropertyWriter writer)
                throws Exception {
            if (writer instanceof BeanPropertyWriter) {
                BeanPropertyWriter bWriter = (BeanPropertyWriter) writer;
                Class<?> type = bWriter.getType().getRawClass();
                if (type == Boolean.class || type == boolean.class) {
                    Object o = bWriter.get(pojo);
                    if (o != null && !(boolean) o) {
                        return;
                    }
                }
            }
            super.serializeAsField(pojo, jgen, provider, writer);
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        Test t = new Test(true, false, true);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setFilters(new SimpleFilterProvider().addFilter("boolean-filter",
                new BooleanPropertyFilter()));
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(t));
    }

}

Output:

{
  "f1" : true,
  "f3" : true,
  "fNull" : null,
  "f4" : "string"
}

OTHER TIPS

Something like Jackson's JSON Views?

There's an issue open for that in Spring's issue tracker.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top