Last active
June 17, 2023 18:15
-
-
Save Jeff-Soares/1ed603fb08d87b6b8a1de35ef11e819d to your computer and use it in GitHub Desktop.
generic enum kserializer for kotlinx.serialization
This file contains hidden or 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
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