I want to remove attributes that have empty collections or null values using gson.
Aiperiodo periodo = periodoService();
//periodo comes fro
I have code that can process array or object with different structure and will remove "empty collections or null values" recursively. It works with String not with Gson directly. If it's not critical, it can help you.
Your code will be:
Aiperiodo periodo = periodoService();
//periodo comes from a service method with a lot of values
Gson gson = new Gson();
String json = gson.toJson(periodo);
json = removeNullAndEmptyElementsFromJson(json);
...
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.util.Iterator;
import java.util.Map;
public class IoJ {
public static void main(String[] args) {
String j = "{\"query\":\"\",\"name\":null,\"result\":{\"searchResult\":[{\"id\":null,\"phone\":\"123456\",\"familyAdditionalDetails\":[],\"probability\":0.0,\"lastUpdated\":\"2019-05-18T12:03:34Z\",\"empty\":false,\"gender\":\"F\"}]},\"time\":1558181014060}";
// {"query":"","name":null,"result":{"searchResult":[{"id":null,"phone":"123456","familyAdditionalDetails":[],"probability":0.0,"lastUpdated":"2019-05-18T12:03:34Z","empty":false,"gender":"F"}]},"time":1558181014060}
System.out.println(j);
// (additional spaces for easier check)
// {"query":"", "result":{"searchResult":[{ "phone":"123456", "probability":0.0,"lastUpdated":"2019-05-18T12:03:34Z","empty":false,"gender":"F"}]},"time":1558181014060}
System.out.println(removeNullAndEmptyElementsFromJson(j));
}
public static String removeNullAndEmptyElementsFromJson(String jsonString) {
if (jsonString == null) {
return jsonString;
}
try {
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonString);
cleanByTree(element);
jsonString = new GsonBuilder().disableHtmlEscaping().create().toJson(element);
return jsonString;
} catch (Exception e) {
return jsonString;
}
}
private static void cleanByTree(JsonElement e1) {
if (e1 == null || e1.isJsonNull()) {
} else if (e1.isJsonArray()) {
for (Iterator it = e1.getAsJsonArray().iterator(); it.hasNext(); ) {
JsonElement e2 = it.next();
if (e2 == null || e2.isJsonNull()) {
//it.remove();
} else if (e2.isJsonArray()) {
if (e2.getAsJsonArray().size() == 0) {
it.remove();
} else {
cleanByTree(e2);
}
} else if (e2.isJsonObject()) {
cleanByTree(e2);
}
}
} else {
for (Iterator> it = e1.getAsJsonObject().entrySet().iterator(); it.hasNext(); ) {
Map.Entry eIt = it.next();
JsonElement e2 = eIt.getValue();
if (e2 == null || e2.isJsonNull()) {
//it.remove();
} else if (e2.isJsonArray()) {
if (e2.getAsJsonArray().size() == 0) {
it.remove();
} else {
cleanByTree(e2);
}
} else if (e2.isJsonObject()) {
cleanByTree(e2);
}
}
}
}
}