Skip to content

Instantly share code, notes, and snippets.

@steliosfran
Created November 17, 2022 10:27
Show Gist options
  • Save steliosfran/18a7721a0246a771c6564b77a4cad818 to your computer and use it in GitHub Desktop.
Save steliosfran/18a7721a0246a771c6564b77a4cad818 to your computer and use it in GitHub Desktop.
inline fun <reified T> createEnumJsonAdapter(): JsonAdapter<T> where T : Enum<T>, T : IEnumValue {
return object : JsonAdapter<T>() {
@FromJson
override fun fromJson(reader: JsonReader): T? {
return if (reader.peek() != JsonReader.Token.NULL) {
enumValues<T>().firstOrNull { it.value == reader.nextInt() }
} else {
reader.nextNull()
}
}
@ToJson
override fun toJson(writer: JsonWriter, value: T?) {
writer.value(value?.value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment