Here's a more in depth example of a class I wrote to remove all false booleans as well as all "false" strings. It was thrown together pretty quickly but seems to work ok. Let me know if there are any bugs you find.
public class RemoveFalseJsonSerializer implements JsonSerializer {
//~ Methods --------------------------------------------------------------------------------------------------------
/**
* serialize
*
* @param object in value
* @param type in value
* @param jsonSerializationContext in value
*
* @return out value
*/
@Override
public JsonElement serialize(Object object, Type type, JsonSerializationContext jsonSerializationContext) {
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(object);
trimJson(jsonElement);
return jsonElement;
}
/**
* We've finally made it to a primitive of some sort. Should we trim it?
*
* @param jsonElement in value
*
* @return out value
*/
private boolean shouldTrimElement(JsonElement jsonElement) {
return jsonElement == null || jsonElement.isJsonNull()
|| (jsonElement.isJsonPrimitive()
&& ((jsonElement.getAsJsonPrimitive().isBoolean() && !jsonElement.getAsBoolean()) // trim false
|| (jsonElement.getAsJsonPrimitive().isString() // also trim the string "false"
&& "false".equalsIgnoreCase(jsonElement.getAsString()))));
}
/**
* trimJson
*
* @param jsonElement in value
*/
private void trimJson(JsonElement jsonElement) {
if (jsonElement == null || jsonElement.isJsonNull() || jsonElement.isJsonPrimitive()) {
return;
}
if (jsonElement.isJsonObject()) {
List toRemove = new ArrayList<>();
JsonObject asJsonObject = jsonElement.getAsJsonObject();
for (Map.Entry jsonElementEntry : asJsonObject.entrySet()) {
if (jsonElementEntry.getValue().isJsonObject() || jsonElementEntry.getValue().isJsonArray()) {
trimJson(jsonElementEntry.getValue());
} else if (shouldTrimElement(jsonElementEntry.getValue())) {
toRemove.add(jsonElementEntry.getKey());
}
}
if (CollectionUtils.isNotEmpty(toRemove)) {
for (String remove : toRemove) {
asJsonObject.remove(remove);
}
}
} else if (jsonElement.isJsonArray()) {
JsonArray asJsonArray = jsonElement.getAsJsonArray();
for (JsonElement element : asJsonArray) {
trimJson(element);
}
}
}
}