如何使用Kotlin enum和Retrofit?
我怎样才能解析JSON模型与枚举?
这是我的枚举类:
enum class VehicleEnumEntity(val value: String) { CAR("vehicle"), MOTORCYCLE("motorcycle"), VAN("van"), MOTORHOME("motorhome"), OTHER("other") }
我需要解析type
为一个枚举
“vehicle”:{“data”:{“type”:“vehicle”,“id”:“F9dubDYLYN”}}
编辑
我试过标准的方式,只是通过我的枚举POJO,它总是空
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") }
资源
另一种选择:使用使用枚举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) }
相同的适配器类可以在其他枚举类上重用。