我有一些枚举值,称为Counter
enum class Counter{
none,
few,
many
}
我想通过改型在模型中获得该枚举的价值,所以我创建了一个对象
data class Test(
var param1: String?,
var param2: String?,
var counter: Counter?,
)
但是当我在Retrofit方法中使用这种模型时,尽管服务器的响应为{"param1": "String1", "param2": "String2", "counter": "many"}
如何获取计数器的值,而不在模型var counter: String?
中使用?
答案 0 :(得分:1)
像这样创建您的枚举
enum class Counter{
@SerializedName("none")
none("none"),
@SerializedName("few")
few("few"),
@SerializedName("many")
many("many")
}
答案 1 :(得分:0)
您可以使用JsonDeserializer
对网络呼叫进行自定义反序列化。
class TestDeserializer: JsonDeserializer<Test> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Test {
val obj = json.asJsonObject
val param1 = obj.get("param1")?.asString
val param2 = obj.get("param2")?.asString
val counter = when(obj.get("counter")?.asString) {
"none" -> Counter.none
"few" -> Counter.few
"many" -> Counter.many
else -> throw IllegalArgumentException("Counter type unknown.")
}
return Test(param1, param2, counter)
}
}
您只需在创建Retrofit客户端时进行注册即可。
val gson = GsonBuilder()
.registerTypeAdapter(Test::class.java, TestDeserializer())
.create()
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()