如何忽略ObjectMapper中的空对象“ {}”而不是空字符串?

时间:2019-08-15 09:18:01

标签: java json jackson fasterxml

我需要序列化(忽略空对象(“ {}”))可以具有任何内容的非结构化对象。

从2.9.X版开始,FasterXML已更改了其适用于(Include.NON_EMPTY)的逻辑。 在旧版本中,它可以按我的需要工作。 但是现在它也忽略了空字符串。

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

假设我们有下一个java对象(为方便起见,它看起来像一个JSON):

{
    "mapA": {},
    "listA": ["",
        {
            "emptyString": "",
            "string": "some text"
        },
        {}
    ],
    "emptyString": "",
    "mapB": {
        "emptyString": "",
        "mapC": {}
    }
}

将其转换为JsonNode:

   mapper.convertValue(/*our Object*/, JsonNode.class);

所需的输出(再次为方便起见,它看起来像一个JSON):

{
    "listA": ["",
        {
            "emptyString": "",
            "string": "some text"
        }
    ],
    "emptyString": "",
    "mapB": {
        "emptyString": ""
    }
}

1 个答案:

答案 0 :(得分:2)

我使用了Include.CUSTOM

    private static class ExludeEmptyObjects{
        @Override
        public boolean equals(Object o) {
            if (o instanceof Map) {
                return ((Map) o).size() == 0;
            }
            if (o instanceof Collection) {
                return ((Collection) o).size() == 0;
            }
            return false;
        }
    }

   ObjectMapper mapper = new ObjectMapper();
   mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
   mapper.setDefaultPropertyInclusion(Value.construct(Include.NON_EMPTY, Include.CUSTOM, null, ExludeEmptyObjects.class));