Solution 1 :
Looking at the documentation I was able to do it myself. Answering here if someone else needs this. We need to use JsonSerializer
provided by Gson to check for values as they are being serialized.
public class SerializeFiles implements JsonSerializer<MyClass> {
@Override
public JsonElement serialize(MyClass src, Type typeOfSrc, JsonSerializationContext context) {
Gson gson = new Gson();
JsonObject object = (JsonObject) gson.toJsonTree(src);
JsonArray arrayA = object.getAsJsonArray("arrayA");
for (JsonElement element : arrayA) {
JsonObject objA = element.getAsJsonObject();
JsonArray arrayB = insObj.getAsJsonArray("arrayB");
for (JsonElement elementB : arrayB) {
JsonObject objB = elementB.getAsJsonObject();
JsonArray arrayC = objB.getAsJsonArray("arrayC");
for(JsonElement elementC : arrayC) {
JsonObject objectC = elementC.getAsJsonObject();
if(objectC.get("base64String") == null) {
arrayC.remove(objB);
}
}
}
return object;
}
}
Problem :
I have a json structure to make from a POJO class like this –
{
"arrayA":[
{
"arrayB":[
{
"arrayC":[
{
"base64String":null
},
{
"base64String":"base 64 value here"
}
]
}
]
}
]
}
As you can see, Objects in arrayC have a field named base64String. Now this base64String may be null sometimes, so while serializing the POJO to json, is there a way to check if this base64String is null and omit that particular object from serializing?