如何在Jackson中序列化时忽略运行时字段

时间:2014-05-13 20:21:11

标签: json spring-mvc serialization jackson

我有一个包含很多布尔字段的bean。我只想将具有真值的那些字段添加到json以节省一些有效负载。这是一项功能,应该基于客户的需求,因此必须以动态的方式完成。我不认为注释会起作用,因为它们是静态的东西。对此有何想法?

2 个答案:

答案 0 :(得分:2)

除了杰克逊的观点之外,您还可以写一个custom Jackson filter来过滤掉所有布尔字段的负值。

以下是一个例子:

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));
    }

}

输出:

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

答案 1 :(得分:0)

类似于Jackson's JSON Views

Spring的问题跟踪器中有an issue open for that