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": ""
}
}
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.