Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
enum class Role(override val value: Int) : IEnumValue {
Admin(1),
Moderator(2)
}
object GenericEnumFactory {
inline fun <reified T> fromValueOrNull(rawValue: Int?): T? where T : Enum<T>, T : IEnumValue {
return enumValues<T>().firstOrNull { it.value == rawValue }
}
}
class RoleEnumJsonAdapter : JsonAdapter<Role>() {
@FromJson
override fun fromJson(reader: JsonReader): Role? {
return if (reader.peek() != JsonReader.Token.NULL) {
GenericEnumFactory.fromValueOrNull(reader.nextInt())
} else {
reader.nextNull()
}
}
@ToJson
override fun toJson(writer: JsonWriter, value: Role?) {
writer.value(value?.value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment