First, you should deserialize json
to a Map<String, Object>
.
Second, loop the map entry to find out what key has null value or what key has value is instance of ArrayList
but empty and remove from the Map
.
Last, serialize the Map
to json
.
Try this code:
String json = "{'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': null, 'e': []}";
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> data = new Gson().fromJson(json, type);
for (Iterator<Map.Entry<String, Object>> it = data.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> entry = it.next();
if (entry.getValue() == null) {
it.remove();
} else if (entry.getValue() instanceof ArrayList) {
if (((ArrayList<?>) entry.getValue()).isEmpty()) {
it.remove();
}
}
}
json = new GsonBuilder().setPrettyPrinting().create().toJson(data);
System.out.println(json);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…