Excluding certain fields from Serialization based on value in GSON
The way to achieve this is by creating custom serializer for the class in question. After allowing Gson to create a JSON object in default fashion, remove the property that you want to exclude based on its value.
public class SerializerForMyClass implements JsonSerializer<MyClass> {
@Override
public JsonElement serialize(MyClass obj, Type type, JsonSerializationContext jsc) {
Gson gson = new Gson();
JsonObject jObj = (JsonObject)gson.toJsonTree(obj);
if(obj.getMyProperty()==0){
jObj.remove("myProperty");
}
return jObj;
}
}
And registering the new serializer in the Gson object that you use for serialization in the application for this class.
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(MyClass.class, new SerializerForMyClass());
Gson gson=gsonBuilder.create();
gson.toJson(myObjectOfTypeMyClass);
This is how I use a type adapter to avoid serializing boolean values that are false
. It avoids creating an additional Gson
instance and does not rely on specific field names.
class MyClassTypeAdapter: JsonSerializer<MyClass>{
override fun serialize(myObject: MyClass, type: Type, context: JsonSerializationContext): JsonElement {
val jsonElement = context.serialize(myObject)
jsonElement.asJsonObject.entrySet().removeAll { it.value is JsonPrimitive && (it.value as JsonPrimitive).isBoolean && !it.value.asBoolean }
return jsonElement
}
}