Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding certain fields from Serialization based on value in GSON

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?

like image 337
Atharva Avatar asked Oct 29 '12 11:10

Atharva


1 Answers

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
   }
}
like image 151
Dabbler Avatar answered Oct 13 '22 00:10

Dabbler