Skip to content

Instantly share code, notes, and snippets.

@vickyturtle
Last active November 14, 2023 20:18
Show Gist options
  • Save vickyturtle/a9b9a747108b4bd93b4d9226c13a201a to your computer and use it in GitHub Desktop.
Save vickyturtle/a9b9a747108b4bd93b4d9226c13a201a to your computer and use it in GitHub Desktop.
Custom Retrofit converter for wrapped responses
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