Skip to content

Instantly share code, notes, and snippets.

@araqnid
Last active March 25, 2021 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save araqnid/c8d4de4ba1577377b5606bf722d7b2c2 to your computer and use it in GitHub Desktop.
Save araqnid/c8d4de4ba1577377b5606bf722d7b2c2 to your computer and use it in GitHub Desktop.
Enum serialization example
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
@Serializable(with=StatusSerializer::class)
enum class Status(val value: Int) {
Ok(0),
NotOk(1),
SomeOtherStatus(2)
}
@Serializable
data class SomeData(val status: Status)
object StatusSerializer : KSerializer<Status> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Status", PrimitiveKind.INT)
override fun serialize(encoder: Encoder, value: Status) {
encoder.encodeInt(value.value)
}
override fun deserialize(decoder: Decoder): Status {
val n = decoder.decodeInt()
return Status.values().find { it.value == n } ?: error("Invalid Status value: $n")
}
}
println(Json.encodeToString(SomeData(status = Status.NotOk)))
println(Json.decodeFromString<SomeData>("""{"status":2}""").toString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment