kotlinx.serialization
kotlinx.serialization copied to clipboard
Serialize Kotlin Generics (Question)
Data Objects
@Serializable
data class BasicApiResponse<T>(
val successful: Boolean,
val message: String? = null,
val data: T? = null
)
@Serializable
data class CalculationsResponse(
val valueA: Double,
val valueB: Double
) {
val valueC: Double get() = valueA * valueB
val valueD: Double = if (valueB > 0) valueA / valueB else 0.0
val valueE: () -> Double = { if (valueB > 0) valueA / valueB else 0.0 }
}
Usage
import io.ktor.http.HttpStatusCode.Companion.OK
val calculation: CalculationsResponse? = calculateService.getCalculation() // Just calling db to get the data
call.respond(status = OK, message = BasicApiResponse<CalculationsResponse>(successful = true, data = calculation))
Expected result
{
"status": 200,
"message": {
"successful": true,
"data": {
"valueA": 10.0,
"valueB": 2.0,
"valueC": 20.0,
"valueD": 5.0,
"valueE": 5.0
}
}
}
NOTE: Explicit type arguments added for clarification
Please supply Sample if possible.
Sorry, I don't get your question. Are you experiencing problems with call.respond()? This is function from ktor, not from kotlinx.serialization. Better ask them then.