Search code examples
kotlinenumsjacksonannotationsmicronaut

How to deserialize Enum value in Kotlin for @QueryValue annotation


I am trying to get lower case letters from Kotlin Enum class when i pass the object in @QueryValue, but i am getting only upper case letters.

I have an enum in data class for example like below:

enum class StudentName{
    @JsonProperty("ram")
    RAM,
    @JsonProperty("sam")
    SAM
}

and i am using that enum like below:

data class StudentParams(
    @JsonProperty("studentName")
    val studentName: StudentName,
    @JsonProperty("age")
    val age: Int
)

I am passing this data class as request object in param value like below

@Post(POST_STUDENT_AGE)
fun postStudentAge(
    studentParams: StudentParams
): String

so in my URL, request object will go in params like --some url--/&studentName=ram&age=20

i need lower case letters from StudentName enum class here but getting only Upper case. When i pass the request object with @body annotation i am getting lower case letters in the request.

I tried enabling ACCEPT_CASE_INSENSITIVE_ENUMS also but didn't work.


Solution

  • Not sure if this would help, but you can convert the enum to String then invoke the toLowerCase(locale) function,

    val ram = StudentName.RAM
    val lowerCasedRam = ram.toString().toLowerCase(Locale.current)
    

    when you pass a StudentParams to your postStudentAge,

    postStudentAge(StudentParams(StudentName.RAM, 1))
    

    you will do something like this.

    fun postStudentAge(
        studentParams: StudentParams
    ) {
        val lowerCaseStudent = studentParams.studentName.toString().toLowerCase(Locale.current)
        
        // use lowercase student 
    }
    

    Calling

    Log.e("StudentName", "$lowerCaseStudent")
    

    prints

    E/StudentName: ram