| // This file was automatically generated from json.md by Knit tool. Do not edit. |
| package example.exampleJson26 |
| |
| import kotlinx.serialization.* |
| import kotlinx.serialization.json.* |
| |
| import kotlinx.serialization.builtins.* |
| |
| @Serializable |
| abstract class Project { |
| abstract val name: String |
| } |
| |
| @Serializable |
| data class BasicProject(override val name: String): Project() |
| |
| |
| @Serializable |
| data class OwnedProject(override val name: String, val owner: String) : Project() |
| |
| object ProjectSerializer : JsonContentPolymorphicSerializer<Project>(Project::class) { |
| override fun selectDeserializer(element: JsonElement) = when { |
| "owner" in element.jsonObject -> OwnedProject.serializer() |
| else -> BasicProject.serializer() |
| } |
| } |
| |
| fun main() { |
| val data = listOf( |
| OwnedProject("kotlinx.serialization", "kotlin"), |
| BasicProject("example") |
| ) |
| val string = Json.encodeToString(ListSerializer(ProjectSerializer), data) |
| println(string) |
| println(Json.decodeFromString(ListSerializer(ProjectSerializer), string)) |
| } |