0

I am using ktor + kotlinx.serialization and i want to achieve a json response from call.respond(Respond("some mesage",null)) something like this :

  • when result = null
{ "message" : "some mesage" }
  • when result is any Type
{ 
"message" : "some mesage",
"result" : "showing result"
}

or

{ 
"message" : "some mesage",
"result" : 0.0
}

  • my Respond data class
@kotlinx.serialization.Serializable
data class Respond<T>(

   @SerialName("message")
   val message : String? = null,

   @SerialName("result")
   val result : T? = null
)

but it giving me an error like this :

Serializer for class 'Respond' is not found.
Mark the class as @Serializable or provide the serializer explicitly.
aeri79
  • 15
  • 6
  • 1
    Have you tried registering a polymorphic serializer? https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#polymorphism-and-generic-classes – aSemy Sep 22 '22 at 15:21
  • haven't and just try it then I achieved by inheritance Respond to make polymorphism that override result with nullable String. thankyouuu – aeri79 Sep 23 '22 at 04:21

1 Answers1

1

I achieved by create inheritance of BaseResponse then polymorphism Response that override type of result with nullable String :

@kotlinx.serialization.Serializable
sealed class BaseResponse<T> {
    abstract val message: String?
    abstract val result: T?
}

@kotlinx.serialization.Serializable
@SerialName("Response")
class Response(
    @SerialName("message") override val message: String?, override val result: String? = null
) : BaseResponse<String>()

@kotlinx.serialization.Serializable
@SerialName("FullResponse")
class FullBaseResponse<T>(
    @SerialName("message") override val message: String?, override val result: T
) : BaseResponse<T>()

val responseModule = SerializersModule {
    polymorphic(BaseResponse::class) {
        subclass(Response.serializer())
        subclass(FullBaseResponse.serializer(PolymorphicSerializer(Any::class)))
    }
}

and added json configuration :

install(ContentNegotiation) {
        json(Json {
            explicitNulls = false
            serializersModule = responseModule
        })
    }

so now I just use call.respond(Respond("some message")) when I only want to show message

aeri79
  • 15
  • 6