Last active
November 14, 2023 20:18
-
-
Save vickyturtle/a9b9a747108b4bd93b4d9226c13a201a to your computer and use it in GitHub Desktop.
Custom Retrofit converter for wrapped responses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CustomConverterFactory(gson: Gson) : Converter.Factory() { | |
private val gsonConverterFactory: GsonConverterFactory = GsonConverterFactory.create(gson) | |
override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? { | |
val wrappedType = object : ParameterizedType { | |
override fun getActualTypeArguments(): Array<Type> = arrayOf(type) | |
override fun getOwnerType(): Type? = null | |
override fun getRawType(): Type = Data::class.java | |
} | |
val gsonConverter: Converter<ResponseBody, *>? = gsonConverterFactory.responseBodyConverter(wrappedType, annotations, retrofit) | |
return ResponseBodyConverter(gsonConverter as Converter<ResponseBody, Data<Any>>) | |
} | |
override fun requestBodyConverter(type: Type?, parameterAnnotations: Array<Annotation>, | |
methodAnnotations: Array<Annotation>, retrofit: Retrofit): Converter<*, RequestBody>? { | |
return gsonConverterFactory.requestBodyConverter(type!!, parameterAnnotations, methodAnnotations, retrofit) | |
} | |
} | |
class ResponseBodyConverter<T>(private val converter: Converter<ResponseBody, Data<T>>) : Converter<ResponseBody, T> { | |
@Throws(IOException::class) | |
override fun convert(responseBody: ResponseBody): T { | |
val response = converter.convert(responseBody) | |
return if (response.statusCode == 0) response.data? else throw ApiException(response.statusCode, response.message?) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment