How to ignore empty Objects "{}" but not empty Strings in ObjectMapper?

Alex Nikulin :

I need to serialize (ignoring empty objects ("{}")) non-structured object which can have any content.

From version 2.9.X FasterXML have changed logic of it work for (Include.NON_EMPTY). In older version it had worked as I need. But now it is ignoring empty strings too.

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

Lets suppose that we have next java object (for convenience it will look like a JSON):

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

Converting it to JsonNode:

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

Desired output(Again for convenience it will look like a JSON):

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

I used 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));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141258&siteId=1