2020-08-18更新:
經(jīng)過使用,發(fā)現(xiàn)之前的版本有幾個問題:
- 轉(zhuǎn)換Kotlin的數(shù)據(jù)類
data class
時藏鹊,會出現(xiàn)JSONException: default constructor not found.
異常,經(jīng)過研究發(fā)現(xiàn)解決辦法有兩個:1呐赡、額外創(chuàng)建一個無參構(gòu)造函數(shù),并使用@JSONCreator
注解。2瑞佩、依賴kotlin-reflect
包 -
FastJson
有Android專用包,(此時最新版本為fastjson:1.1.72.android
)坯台,比完整包減少了一些無用代碼和功能炬丸,但是實(shí)測使用時,當(dāng)屬性類型為List會報(bào)set property error
的異常蜒蕾,因此不推薦使用稠炬。
話不多說直接上代碼,首先依賴如下:
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
implementation "com.alibaba:fastjson:1.2.73"
- FastJsonConverterFactory.kt
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type
class FastJsonConverterFactory private constructor() : Converter.Factory() {
override fun responseBodyConverter(
type: Type,
annotations: Array<Annotation>,
retrofit: Retrofit
): Converter<ResponseBody, *>? {
return FastJsonResponseBodyConverter<Any>(type)
}
override fun requestBodyConverter(
type: Type,
parameterAnnotations: Array<Annotation>,
methodAnnotations: Array<Annotation>,
retrofit: Retrofit
): Converter<*, RequestBody>? {
return FastJsonRequestBodyConverter<Any>()
}
companion object {
fun create(): FastJsonConverterFactory {
return FastJsonConverterFactory()
}
}
}
- FastJsonRequestBodyConverter.kt
import com.alibaba.fastjson.JSON
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.Converter
class FastJsonRequestBodyConverter<T> : Converter<T, RequestBody> {
private val MEDIA_TYPE = "application/json; charset=UTF-8".toMediaType()
override fun convert(value: T): RequestBody? {
val jsonStr = JSON.toJSONString(value)
return jsonStr.toRequestBody(contentType = MEDIA_TYPE)
}
}
- FastJsonResponseBodyConverter.kt
import com.alibaba.fastjson.JSON
import okhttp3.ResponseBody
import retrofit2.Converter
import java.lang.reflect.Type
class FastJsonResponseBodyConverter<T>(
private val type: Type
) : Converter<ResponseBody, T> {
override fun convert(value: ResponseBody): T? {
return value.use {
JSON.parseObject(value.string(), type)
}
}
}
使用時就是簡單的添加就行
val retrofit = Retrofit.Builder()
.baseUrl("http://www.example.com/")
.addConverterFactory(FastJsonConverterFactory.create())
.build()