Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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": ""
    }
}
like image 662
Alex Nikulin Avatar asked Jan 22 '26 20:01

Alex Nikulin


1 Answers

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));
like image 133
Alex Nikulin Avatar answered Jan 25 '26 08:01

Alex Nikulin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!