I am using GSON for my serialization purposes, I am not finding a way of excluding certain fields from serialization based on ExclusionStrategy class provided by Gson based on the value of field, as it only supports top level class or field attributes based exclusions. The field attributes do not include the value of that field. So what should I do?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With