[REQ] [kotlin][jvm-retrofit2] Add handling if responseBody is empty string
Is your feature request related to a problem? Please describe.
JsonParser throws an exception when ResponseBody is an empty string. (In my case I use kotlinx_serialization.) https://github.com/square/retrofit/issues/1554
Describe the solution you'd like
this case we need a way to handle empty strings.
Describe alternatives you've considered
Add [pre]converterFactory
which can be called first in retrofitBuilder
inside ApiClient. There is already converterFactory
but it is not available in this case because it is added last.
private val retrofitBuilder: Retrofit.Builder by lazy {
Retrofit.Builder()
.baseUrl(baseUrl)
//////////// add //////////
.apply {
if (preConverterFactory != null) {
addConverterFactory(preConverterFactory)
}
}
///////////////////////////////
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(kotlinxSerializationJson.asConverterFactory("application/json".toMediaType()))
.apply {
if (converterFactory != null) {
addConverterFactory(converterFactory)
}
}
}
This allows you to add converters to suit your project's needs.
(In my case, adding NullOnEmptyConverterFactory
can solve the problem.)
class NullOnEmptyConverterFactory : Converter.Factory() {
override fun responseBodyConverter(
type: Type,
annotations: Array<out Annotation>,
retrofit: Retrofit
): Converter<ResponseBody, *> {
val delegate: Converter<ResponseBody, *> = retrofit.nextResponseBodyConverter<Any?>(
this, type, annotations
)
return Converter<ResponseBody, Any?> { body ->
when (body.contentLength() == 0L) {
true -> null
else -> delegate.convert(body)
}
}
}
}
This way, you can handle the response to suit your own requirements.