繁体   English   中英

Kotlin Android嵌套级别数据class如何自定义Retrofit转换器工厂?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM