#!/usr/bin/env kotlin // not yet supported // @file:CompilerOptions("-Xplugin=kotlin-serialization-compiler-plugin.jar") @file:Repository("https://repo.maven.apache.org/maven2") @file:DependsOn( "org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0" ) import kotlinx.serialization.* import kotlinx.serialization.json.* val json = Json { ignoreUnknownKeys = true prettyPrint = true } val command = args .firstOrNull() ?.lowercase() ?.let { Commands.of(it) } when (command) { Commands.Deserialize -> deserialize() Commands.Serialize -> serialize() else -> { val name = (this::class.simpleName ?: "*") .lowercase() .replace("_main", "") .replace("_", "-") .let { "${it}.main.kts" } val cmds = Commands.entries .joinToString(separator = "|", prefix = "<", postfix = ">") { it.name.lowercase() } "Usage: $name $cmds" } }.also { result -> println(result) } fun deserialize(): String { val serialized = """ { "int": 42, "bool": true, "string": "cool", "nullable": null } """.trimIndent() val deserialized = json.decodeFromString(serialized) return deserialized.toString() } fun serialize(): String { val deserialized = Data( 42, true, "cool", null, ) val serialized = json.encodeToString(deserialized) return serialized } enum class Commands { Deserialize, Serialize; companion object { fun of(value: String?) = entries.find { it.name.lowercase() == value?.lowercase() } } } @Serializable data class Data( val int: Int, val bool: Boolean, val string: String, val nullable: String?, )