Created
November 17, 2018 15:40
-
-
Save Benjiko99/06cfb6faec1066cead1e76c57da94837 to your computer and use it in GitHub Desktop.
Serialization and deserialization of a generic type in gson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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