Skip to content

Instantly share code, notes, and snippets.

@s3va
Last active September 7, 2024 16:55
Show Gist options
  • Save s3va/ef0f5c92082a027429cd8bd641d879e8 to your computer and use it in GitHub Desktop.
Save s3va/ef0f5c92082a027429cd8bd641d879e8 to your computer and use it in GitHub Desktop.
koltin serialization polymorphizm. "type" field in json
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.*
import kotlinx.serialization.SerialName
@Serializable
@JsonClassDiscriminator("mytype")
sealed class ContentRequest
@Serializable
data class MessageRequest (
val type : String = "text",
val text : String
) : ContentRequest()
@Serializable
@SerialName("another type")
data class AnotherRequest (
val type : String = "very important text",
val text : String
) : ContentRequest()
fun main() {
val messageRequest = MessageRequest("one","two")
val contentRequest: ContentRequest = MessageRequest("one","two")
val anotherRequest: ContentRequest = AnotherRequest("one","two")
println(Json.encodeToString(messageRequest)) // {"type":"one","text":"two"}
println(Json.encodeToString(contentRequest)) // {"mytype":"MessageRequest","type":"one","text":"two"}
println(Json.encodeToString(anotherRequest)) // {"mytype":"another type","type":"one","text":"two"}
}
@s3va
Copy link
Author

s3va commented Sep 7, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment