Last active
September 7, 2024 16:55
-
-
Save s3va/ef0f5c92082a027429cd8bd641d879e8 to your computer and use it in GitHub Desktop.
koltin serialization polymorphizm. "type" field in json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://pl.kotl.in/ryUXNfOsv