use of enum in retrofit response with Kotlin

Viewed 18

I am building an app with retrofit and I have a data class to represent the model.

data class RetrofitModel(
    @SerializedName("lock_status") val lockStatus: LockStatus,
    @SerializedName("door_status") val doorStatus: DoorStatus,
)

@Keep
enum class LockStatus(status: String) {
    Unlocked("Unlocked"),
    Locked("Locked")
}

@Keep
enum class DoorStatus(status: String) {
    DoorOpen("door_open"),
    DoorClose("close")
}

Overall the the code works fine but when I try later to extract the value of the DoorStatus class, it doesn't work for the door_open

if I do a lockStatus.name I will get Unlocked or Locked depending on the status received but for doorStatus.name I got close but if the status is door_open I have a null value.

As soon as _ is there, it's not working.

Any idea?

1 Answers

I am not sure why its not working with underscore.Because json serialization/deserialization works for multiple naming styles like underscrore/camelcase ...

Several things you can try.

  1. Adding serializedName annotation to the enum values.
enum class DoorStatus(status: String) {
    @SerializedName("door_open")
    DoorOpen("door_open"),
    @SerializedName("close")
    DoorClose("close")
}
  1. Camel casing the value name. I think Usually it would detect the field even its in different naming convention with same name. So door_open will be mapped to doorOpen.

    enum class DoorStatus(status: String) {
     DoorOpen("doorOpen"),
     DoorClose("close")
    }
    
Related