Skip to content

Instantly share code, notes, and snippets.

@Jeff-Soares
Last active June 17, 2023 18:15
Show Gist options
  • Save Jeff-Soares/1ed603fb08d87b6b8a1de35ef11e819d to your computer and use it in GitHub Desktop.
Save Jeff-Soares/1ed603fb08d87b6b8a1de35ef11e819d to your computer and use it in GitHub Desktop.
generic enum kserializer for kotlinx.serialization
abstract class EnumSerializer<T : Enum<T>>(values: Array<out T>, private val defaultValue: T) : KSerializer<T> {
private val lookup = values.associateBy({ it }, { it.serialName })
private val revLookup = values.associateBy { it.serialName.uppercase() }
override val descriptor = PrimitiveSerialDescriptor(values.first()::class.qualifiedName!!, PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: T) = encoder.encodeString(lookup.getValue(value))
override fun deserialize(decoder: Decoder) = revLookup[decoder.decodeString().uppercase()] ?: defaultValue
private val Enum<T>.serialName: String
get() = this::class.java.getField(this.name).getAnnotation(SerialName::class.java)?.value ?: name
}
// Usage example
@Serializable(with = PrioritySerializer::class)
enum class Priority {
@SerialName("highest")
HIGH,
MEDIUM,
LOW,
NO_PRIORITY
}
object PrioritySerializer : EnumSerializer<Priority>(values = Priority.values(), defaultValue = Priority.NO_PRIORITY)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment