代码之家  ›  专栏  ›  技术社区  ›  Dariusz

杰克逊包括。字段不工作时NOT\U NULL

  •  0
  • Dariusz  · 技术社区  · 8 年前

    使用 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 回复  |  直到 8 年前
        1
  •  1
  •   Dariusz    8 年前

    使用

    @JsonInclude(Include.NON_NULL)
    

    而不是

    @JsonInclude(content=Include.NON_NULL)
    

    作品谢谢@Aaron。