简体   繁体   English

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

[英]How to customize Retrofit converter factory for nested level data class in Kotlin Android?

For example, my model class name is StudentResponse比如我的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()
        }
    }
}

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.所以这里的类型是 StudentResponse。 So the pojo structure is like this inside StudentResponse - List - Books.kt - var bookValue: Double所以 pojo 结构在 StudentResponse 中是这样的 - List - Books.kt - var bookValue: Double

But what I want is: Double to Int inside StudentResponse - List - Books.kt - var bookValue: Double但我想要的是:StudentResponse 中的 Double to Int - 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?不仅仅是这个例子,Foe整个项目这种类型的很多变化都会来那么有什么用呢? ::retrofit converter factory vs gson deserialization ::retrofit转换器工厂与gson反序列化

I appreciate all answers!我感谢所有答案!

If you just need your Double response to be an Int, you can use a @JsonAdapter to achieve that.如果您只需要将 Double 响应设为 Int,则可以使用 @JsonAdapter 来实现。

Change your Books class to:将您的图书 class 更改为:

data class Books(
    @JsonAdapter(DoubleToInt::class)
    var bookValue: Int?, 

And add this class to handle the conversion:并添加这个 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