kotlinkotlinx.serialization

How to access every SerialName associated with each enum constant in an enum class?


I have a data class that I want to make serializable

data class ClassTemp (
    val str: String,
    val tmp: Temp,
)
@Serializable
enum class Temp {
    @SerialName("Serial Name - 1")
    S1,
    @SerialName("Serial Name - 2")
    S2
}

Example JSON that I want to deserialize and it's corresponding ClassTemp object

{
    "str": "Some String",
    "tmp": "Serial Name - 1",
}
ClassTemp(
    str: "Some String"
    tmp: Temp.S1
)

Now the problem is not specifically about serializing and deserializing since that's working fine. It's just that for the given enum class Temp How would I get all the SerialNames that are in it?

[ "Serial Name - 1", "Serial Name - 2" ]

Solution

  • You can use reflection to get the annotation values of each enum field:

    val serialNames = Temp.values().map { 
      Temp::class.java.getField(it.name).getAnnotation(SerialName::class.java)?.value 
    }