Does serialization not support generics? I am work...
# serialization
g
Does serialization not support generics? I am working on a multiplatform project (Targetting Android and JS) -
Copy code
@Serializable
class BaseResponse<T> {

    val data: T? = null

    @SerialName("status")
    val isSuccess: Boolean = false

    @SerialName("session")
    val isSessionExpire: Boolean = false

    @SerialName("message")
    val message: String = ""
}
Can this be serialized -
BaseResponse<String>
? There is an error logged ->
Copy code
java.lang.UnsupportedOperationException: The only generic classes supported for now are standard collections
got class class dto.BaseResponse (Kotlin reflection is not available)
I did read the documentation regarding requiring a custom serializer in case of generics but wasn't able to understand it. Any help would be much appreciated.
⬆️ 1
r
I have been able to serialize generics, the serialization call looks something like this:
Copy code
val jsonString: String = json.stringify(
  BaseResponse.serializer(
    String.serializer()
  ),
  baseResponseInstance
)
That json instance is of type kotlinx.serialization.json.Json
g
@rnentjes Sorry, I meant to deserialize to BaseResponse<T>.
r
I think you need to know the type of T before you can do that (because of type erasure), but it can be just a super type. So if you can let the content of your responses all inherit from some super class you can make this work.