如何使用Kotlin enum与Retrofit?

Dra*_*ake 11 enums android gson kotlin retrofit2

如何使用枚举将JSON解析为模型?

这是我的枚举类:

enum class VehicleEnumEntity(val value: String) {
   CAR("vehicle"),
   MOTORCYCLE("motorcycle"),
   VAN("van"),
   MOTORHOME("motorhome"),
   OTHER("other")
}
Run Code Online (Sandbox Code Playgroud)

我需要解析type一个枚举

"vehicle":{"data":{"type":"vehicle","id":"F9dubDYLYN"}}

编辑

我已经尝试过标准方法,只需将我的枚举传递给POJO,它总是为空

Lor*_*nMK 34

enum class VehicleEnumEntity(val value: String) {
   @SerializedName("vehicle")
   CAR("vehicle"),

   @SerializedName("motorcycle")
   MOTORCYCLE("motorcycle"),

   @SerializedName("van")
   VAN("van"),

   @SerializedName("motorhome")
   MOTORHOME("motorhome"),

   @SerializedName("other")
   OTHER("other")
}
Run Code Online (Sandbox Code Playgroud)

资源

  • 这是一个 GSON 解决方案,将 moshi 更改为 `@Json(name="foo")` (6认同)

eph*_*ent 6

另一种选择:使用使用value枚举的自定义(de)序列化程序,而不是name(默认).这意味着您不需要注释每个枚举值,而是可以注释枚举类(或添加适配器GsonBuilder).

interface HasValue {
    val value: String
}

@JsonAdapter(EnumByValueAdapter::class)
enum class VehicleEnumEntity(override val value: String): HasValue {
   CAR("vehicle"),
   MOTORCYCLE("motorcycle"),
   VAN("van"),
   MOTORHOME("motorhome"),
   OTHER("other")
}

class EnumByValueAdapter<T> : JsonDeserializer<T>, JsonSerializer<T>
    where T : Enum<T>, T : HasValue {
    private var values: Map<String, T>? = null

    override fun deserialize(
        json: JsonElement, type: Type, context: JsonDeserializationContext
    ): T? =
        (values ?: @Suppress("UNCHECKED_CAST") (type as Class<T>).enumConstants
            .associateBy { it.value }.also { values = it })[json.asString]

    override fun serialize(
        src: T, type: Type, context: JsonSerializationContext
    ): JsonElement = JsonPrimitive(src.value)
}
Run Code Online (Sandbox Code Playgroud)

相同的适配器类可以在其他枚举类上重用.