JakeWharton/retrofit2-kotlinx-serialization-converter

Serializer for class ResponseBody?

fessNiklas opened this issue · 1 comments

How to serialize this?

@Serializable
data class BaseResponse<T>(
    val code: Int,
    val message: String?,
    val result: T? = null
)
@GET(...)
fun foo(...): Call<BaseResponse<ResponseBody>>

The server passes the error code only to the BaseResponse class. This code will certainly not work. At the compilation stage, I see an error:
Can't locate argument-less serializer for class ResponseBody. For generic classes, such as lists, please provide serializer explicitly.
What should I do to get this to work?

You would need to teach kotlinx.serialization how to create the ResponseBody type, either through one of its static factory functions or with your own subclass. It is only supported by Retrofit when it is directly defined as the body type. Since you've defined BaseResponse<ResponseBody> as the body type, Retrofit asks kotlinx.serialization to convert the raw bytes into that type and thus it needs to know how to create every type in that object. You can read about the many ways of defining custom serializers here: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/custom_serializers.md