Skip to content

Instantly share code, notes, and snippets.

@Benjiko99
Created November 17, 2018 15:40
Show Gist options
  • Save Benjiko99/06cfb6faec1066cead1e76c57da94837 to your computer and use it in GitHub Desktop.
Save Benjiko99/06cfb6faec1066cead1e76c57da94837 to your computer and use it in GitHub Desktop.
Serialization and deserialization of a generic type in gson
data class UniqueIdentifier<out T>(val value: T)
typealias TransactionId = UniqueIdentifier<Int>
class UniqueIdentifierAdapter : JsonSerializer<UniqueIdentifier<*>>, JsonDeserializer<UniqueIdentifier<*>> {
override fun serialize(
src: UniqueIdentifier<*>,
typeOfSrc: Type,
context: JsonSerializationContext
): JsonElement {
return context.serialize(src.value)
}
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext
): UniqueIdentifier<*> {
val value = context.deserialize<Any>(json, typeOfT.javaClass.genericSuperclass)
return UniqueIdentifier(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment