2020-08-18更新:
经过使用,发现之前的版本有几个问题:
- 转换Kotlin的数据类
data class
时,会出现JSONException: default constructor not found.
异常,经过研究发现解决办法有两个:1、额外创建一个无参构造函数,并使用@JSONCreator
注解。2、依赖kotlin-reflect
包 -
FastJson
有Android专用包,(此时最新版本为fastjson:1.1.72.android
),比完整包减少了一些无用代码和功能,但是实测使用时,当属性类型为List会报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()