Thread
#serialization
    Gurupad Mamadapur [FH]

    Gurupad Mamadapur [FH]

    2 years ago
    Does serialization not support generics? I am working on a multiplatform project (Targetting Android and JS) -
    @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 ->
    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.
    r

    rnentjes

    2 years ago
    I have been able to serialize generics, the serialization call looks something like this:
    val jsonString: String = json.stringify(
      BaseResponse.serializer(
        String.serializer()
      ),
      baseResponseInstance
    )
    That json instance is of type kotlinx.serialization.json.Json
    Gurupad Mamadapur [FH]

    Gurupad Mamadapur [FH]

    2 years ago
    @rnentjes Sorry, I meant to deserialize to BaseResponse<T>.
    r

    rnentjes

    2 years ago
    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.