杰克逊Include.NOT_NULL在场上无法正常工作

时间:2018-03-12 13:02:31

标签: java jackson lombok

使用JsonInclude(content=Include.NON_NULL)(或实际上任何其他JsonInclude选项)似乎对我的对象的序列化没有影响。考虑这个测试:

public class JsonTest {
    @Data
    @JsonInclude(content=Include.ALWAYS)
    static class TestObj {
        String fieldVisible = "a";
        String fieldVisibleNull = null;
        @JsonInclude(content=Include.NON_NULL)
        String fieldInvisible = null;
    }

    public static void main(String[] args) throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writerFor(TestObj.class).writeValueAsString(new TestObj());
        if (json.contains("fieldInvisible")) {
            System.err.println(json);
            throw new RuntimeException("null field written even though it shouldn't be");
        }
    }
}

结果是:

{"fieldVisible":"a","fieldVisibleNull":null,"fieldInvisible":null}
Exception in thread "main" java.lang.RuntimeException: null field written even though it shouldn't be
    at my.package.JsonTest.main(JsonTest.java:57)

我缺少什么?我不理解什么?

1 个答案:

答案 0 :(得分:1)

使用

@JsonInclude(Include.NON_NULL)

而不是

@JsonInclude(content=Include.NON_NULL)

作品。谢谢@Aaron。