代码拉取完成,页面将自动刷新
package com.catchpig.mvvm.network.converter
import com.catchpig.annotation.interfaces.SerializationConverter
import com.catchpig.mvvm.network.data.IResponseData
import kotlinx.serialization.KSerializer
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.serializer
import okhttp3.ResponseBody
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlin.reflect.KClass
open abstract class BaseResponseBodyConverter :
SerializationConverter<ResponseBody, Any> {
companion object {
private const val LIST_EMPTY = "[]"
private const val MAP_EMPTY = "{}"
private const val STRING_EMPTY = "\"\""
private const val NUMBER_ZERO = "0"
}
lateinit var type: Type
abstract fun getResultClass(): KClass<out IResponseData<JsonElement>>
override fun convert(value: ResponseBody): Any? {
val valueString = value.string()
val kSerializer: KSerializer<Any> =
serializer(getResultClass().java)
val result: IResponseData<JsonElement> =
json.decodeFromString(kSerializer, valueString) as IResponseData<JsonElement>
when (result.getErrorCode()) {
result.isSuccess() -> {
val data = result.data()
return if (data == null) {
json.decodeFromString(serializer(type), checkType(type))
} else {
json.decodeFromString(serializer(type), json.encodeToString(data))
}
}
else -> throw handlerErrorCode(result.getErrorCode(), result.getErrorMessage())
}
}
abstract fun handlerErrorCode(errorCode: String, msg: String): Exception
private fun checkType(type: Type): String {
return when (type) {
is ParameterizedType -> {
when (type.rawType) {
List::class.java -> {
LIST_EMPTY
}
else -> {
MAP_EMPTY
}
}
}
String::class.java -> {
STRING_EMPTY
}
Int::class.java,
Double::class.java,
Float::class.java,
Long::class.java -> {
NUMBER_ZERO
}
else -> {
MAP_EMPTY
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。