Excluding certain fields from Serialization based on value in GSON

前端 未结 3 915
夕颜
夕颜 2020-12-28 23:01

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

3条回答
  •  一个人的身影
    2020-12-28 23:25

    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{
       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
       }
    }
    

提交回复
热议问题