[英]How to customize Retrofit converter factory for nested level data class in Kotlin Android?
比如我的model class 名字是StudentResponse
class BaseConverterFactory private constructor() : Converter.Factory() {
override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? {
LogUtils.d("Hello type: " + type)
if (type === String::class.java) {
return Converter { value -> value.string() }
} else if (type === Int::class.java) {
return Converter { value -> Integer.valueOf(value.string()) }
} else if (type === Double::class.java) {
return Converter { value -> java.lang.Double.valueOf(value.string()) }
} else if (type === Boolean::class.java) {
return Converter { value -> java.lang.Boolean.valueOf(value.string()) }
}
return null
}
companion object {
fun create(): BaseConverterFactory {
return BaseConverterFactory()
}
}
}
代碼:
data class StudentResponse(
var aggregatedValues: List<Books>?,
}
data class Books(
var bookValue: Double?, //here retrofit should consider as int. If 34.11 is coming it should round off to 34
所以這里的類型是 StudentResponse。 所以 pojo 結構在 StudentResponse 中是這樣的 - List - Books.kt - var bookValue: Double
但我想要的是:StudentResponse 中的 Double to Int - List - Books.kt - var bookValue: Double
我無法使用我的自定義轉換器工廠執行此操作
另外,哪種方法更好? 不僅僅是這個例子,Foe整個項目這種類型的很多變化都會來那么有什么用呢? ::retrofit轉換器工廠與gson反序列化
我感謝所有答案!
如果您只需要將 Double 響應設為 Int,則可以使用 @JsonAdapter 來實現。
將您的圖書 class 更改為:
data class Books(
@JsonAdapter(DoubleToInt::class)
var bookValue: Int?,
並添加這個 class 來處理轉換:
class DoubleToInt : JsonDeserializer<Int?> {
override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?
): Int? {
return json?.asDouble?.roundToInt()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.