For example, my model class name is 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()
}
}
}
Code:
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
So here type is coming as StudentResponse. So the pojo structure is like this inside StudentResponse - List - Books.kt - var bookValue: Double
But what I want is: Double to Int inside StudentResponse - List - Books.kt - var bookValue: Double
that I'm not able to do this using my custom converter factory
Also, which is a better approach? not just for this example, Foe entire project this type of many changes will come so what to use? ::retrofit converter factory vs gson deserialization
I appreciate all answers!
If you just need your Double response to be an Int, you can use a @JsonAdapter to achieve that.
Change your Books class to:
data class Books(
@JsonAdapter(DoubleToInt::class)
var bookValue: Int?,
And add this class to handle the conversion:
class DoubleToInt : JsonDeserializer<Int?> {
override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?
): Int? {
return json?.asDouble?.roundToInt()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.